How to find the number of decimal places in double?

For example, there is a double number with a value of 12.345. How can I quickly find out and save in a variable the number of decimal places?

Thank you in advance!

double x = 12.345; int i = 0; 

    4 answers 4

     double x = 12.345; String[] splitter = String.valueOf(x).split("\\."); int i = splitter[1].length(); //splitter[0].length() Это вернет нам количество знаков до запятой 
    • Writes an error: Cannot invoke toString () on the primitive type double - Slava Epifanov
    • That should work, I checked with Double, not double :) - nick_gabpe

    Can be done as follows:

     System.out.println(BigDecimal.valueOf(0.12345).scale()); // 5 

    Also works for very large numbers as a string:

     System.out.println(new BigDecimal("2321.1234567890123456789").scale()); // 19 

    Only you need to be wary of using new BigDecimal(double) , you can get unexpected values ​​due to the fact that double doesn’t always contain exactly what we put there, but something very similar (some values ​​cannot be represented exactly in binary):

     BigDecimal d = new BigDecimal(0.123); System.out.println(d.scale()); // 52 ??? System.out.println(d.toString()); // 0.1229999999999999982236431605997495353221893310546875 !!! 
    • It should be without translation into the string. And so the answer is good! - Slava Epifanov
    • @SlavaEpifanov BigDecimal.valueOf(0.12345).scale() works without translating into a string. - Alex Chermenin
     Double x = 12.345 Srting dstring = x.toString() int decimalLen = dstring.length()-(dstring.indexOf(".")+1) 
    • THAT is terrible ... Double-> String-> length indexof ......... I certainly understand this is written quickly, but do not teach the bad. - Denis Kotlyarov
    • @Denis Kotlyarov the author didn’t show, quickly what ... quickly write code or code that quickly calculates it ... - Lex Hobbit

    In a cycle, you multiply by 10 and increment the counter while x! = Int (x)

    • This hardcode is called !!! - Slava Epifanov
    • @SlavaEpifanov hardcode is not here, are you talking about? - Kromster