Search code examples
javafloating-pointintegerdouble

How to get the number of decimal digits from a double in Java? (Ex: 2.34 => 2 , 2.340 => 2 , 0.921 => 3)


Title is self-explanatory. What is a good way, with just math preferably, to get the number of digits from a Java double?

123 => 0
1.12 => 2
1.0001 => 4
2.340000 => 2
0.10 => 1

I have a double d = 0.320 for example.

As far as I know, for the compiler / jvm / computer:

System.out.println(0.0100000 == 0.01); // prints true...

Solution

  • This should get the amount after the dec:

     Double d = 123.9343;
     String[] div = d.toString().split("\\.");
     div[0].length();   // Before Decimal Count
     div[1].length();   // After  Decimal Count   
    

    Explanation: You first turn the double into a string and use the split function to split the string from the .
    Once it is in 2 pieces you can then find the length of the string easily with the length function.