How many decimal Places in A Double (Java)

前端 未结 7 1007
南方客
南方客 2020-11-30 14:19

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         


        
7条回答
  •  感动是毒
    2020-11-30 14:35

    From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.

    I wrote a tiny bit of code to test that.

    public class test {
        public static void main(String[] args) {
            double x;`enter code here`
            x = 3411.999999999999;
            System.out.println("16: "+x);   // gives 3411.999999999999
            x = 3411.9999999999999;
            System.out.println("17: "+x);   // gives 3412.0
            x = 0.9999999999999999;
            System.out.println("16: "+x);   // gives 0.9999999999999999
            x = 0.99999999999999999;
            System.out.println("17: "+x);   // gives 1.0
        }  
    }
    

    There 4+12 = 16 digits. A run outputs 3411.999999999999.

    Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.

    The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).

    Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.

    Hope this helps.

提交回复
热议问题