Number of decimal digits in a double

A double is not always an exact representation. You can only say how many decimal places you would have if you converted it to a String.

double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;

This will only work for numbers which are not turned into exponent notation. You might consider 1.0 to have one or no decimal places.


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

    String s = "" + 234.12413;
    String[] result = s.split("\\.");
    System.out.println(result[0].length() + " " + result[1].length());

Tags:

Double

Java