Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many significant digits do floats and doubles have in java?

Does a float have 32 binary digits and a double have 64 binary digits? The documentation was too hard to make sense of.

Do all of the bits translate to significant digits? Or does the location of the decimal point take up some of the bits?

like image 656
Eamon Moloney Avatar asked Nov 24 '12 16:11

Eamon Moloney


People also ask

How many significant digits does a float have?

Float values have between 6 and 9 digits of precision, with most float values having at least 7 significant digits. Double values have between 15 and 18 digits of precision, with most double values having at least 16 significant digits.

How many significant digits are in double precision?

A double-precision floating point number carries fifteen significant digits.

How many precision digits does a float have?

float has 7 decimal digits of precision.


1 Answers

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

like image 160
marcus Avatar answered Sep 18 '22 23:09

marcus