How many decimal Places in A Double (Java)

Is there any in built function in java to tell me how many decimal places in a double. For example:

101.13 = 2
101.130 = 3
1.100 = 3
1.1 = 1
-3.2322 = 4 etc.

I am happy to convert to another type first if needed, I have looked at converting to bigdecimal first with no luck.


You could use BigDecimal.scale() if you pass the number as a String like this:

BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3

but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:

String[] s = "1.31".split("\\.");
System.out.println(s[s.length - 1].length());

Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31 and 1.310 (they're exactly the same double) like others have pointed out as well.


No.

1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double).

Therefore you can't ever get that kind of information from a double.

The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double value. And that is as easy as calling Double.toString() and checking how many decimal digits there are.


The number of decimal places in a double is 16.

64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.

See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.

double, whose values include the 64-bit IEEE 754 floating-point numbers.

See http://en.wikipedia.org/wiki/IEEE_754-2008