How to find the number of decimal places in double?
For example, there is a double number with a value of 12.345. How can I quickly find out and save in a variable the number of decimal places?
Thank you in advance!
double x = 12.345; int i = 0; How to find the number of decimal places in double?
For example, there is a double number with a value of 12.345. How can I quickly find out and save in a variable the number of decimal places?
Thank you in advance!
double x = 12.345; int i = 0; double x = 12.345; String[] splitter = String.valueOf(x).split("\\."); int i = splitter[1].length(); //splitter[0].length() Это вернет нам количество знаков до запятой Can be done as follows:
System.out.println(BigDecimal.valueOf(0.12345).scale()); // 5 Also works for very large numbers as a string:
System.out.println(new BigDecimal("2321.1234567890123456789").scale()); // 19 Only you need to be wary of using new BigDecimal(double) , you can get unexpected values due to the fact that double doesn’t always contain exactly what we put there, but something very similar (some values cannot be represented exactly in binary):
BigDecimal d = new BigDecimal(0.123); System.out.println(d.scale()); // 52 ??? System.out.println(d.toString()); // 0.1229999999999999982236431605997495353221893310546875 !!! BigDecimal.valueOf(0.12345).scale() works without translating into a string. - Alex Chermenin Double x = 12.345 Srting dstring = x.toString() int decimalLen = dstring.length()-(dstring.indexOf(".")+1) In a cycle, you multiply by 10 and increment the counter while x! = Int (x)
Source: https://ru.stackoverflow.com/questions/694717/
All Articles