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

前端 未结 6 1361
余生分开走
余生分开走 2020-11-22 09:28

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 d

6条回答
  •  不思量自难忘°
    2020-11-22 09:54

    From java specification :

    The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

    As it's hard to do anything with numbers without understanding IEEE754 basics, here's another link.

    It's important to understand that the precision isn't uniform and that this isn't an exact storage of the numbers as is done for integers.

    An example :

    double a = 0.3 - 0.1;
    System.out.println(a);          
    

    prints

    0.19999999999999998
    

    If you need arbitrary precision (for example for financial purposes) you may need Big Decimal.

提交回复
热议问题