Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many decimal Places in A Double (Java)

Tags:

java

rounding

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.

like image 409
Karl Avatar asked Jul 26 '10 10:07

Karl


People also ask

How many decimal places is a double?

double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.

How many digits can double hold Java?

This is possible to do because a float value can hold only a maximum of 7 digits after the decimal, while a double value in Java can hold a maximum of 16 digits after the decimal.

Is a double in Java a decimal?

Double data type stores decimal values with 15-16 digits of precision. The default value is 0.0d; this means that if you do not append f or d to the end of the decimal, the value will be stored as a double in Java.

How many bits are doubles in Java?

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification.


2 Answers

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

like image 169
S.Lott Avatar answered Oct 24 '22 06:10

S.Lott


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.

like image 25
Joachim Sauer Avatar answered Oct 24 '22 06:10

Joachim Sauer