How many decimal Places in A Double (Java)

You could use BigDecimal.scale() if you pass the number as a String like this:

BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3

but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:

String[] s = "1.31".split("\\.");
System.out.println(s[s.length - 1].length());

Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can’t differentiate between 1.31 and 1.310 (they’re exactly the same double) like others have pointed out as well.

Leave a Comment