In this post, we will see how to count number of decimal places in java.
A Double can not have exact representation, you need to convert it to String to count number of decimal places in Java.
There are multiple ways to count number of decimal places in java. Let’s go through them.
Using String’s split() method
To count number of decimal places using String’s split() method:
- Convert
DoubletoStringusingDouble.toString(). - Split the String by dot(.) and assign it to String array
strArr. - Get number of decimal places using
strArr[1].length.
package org.arpit.java2blog;
public class CountNumberOfDecimalPlacesMain {
public static void main(String[] args) {
Double d= 122.434548;
String doubleStr = Double.toString(Math.abs(d));
String[] strArr = doubleStr.split("\\.");
System.out.println("Number of decimal places in 122.434548: "+strArr[1].length());
}
}
Output
Number of decimal places in 122.434548: 6
Further reading:
Using String’s indexof() method
To count number of decimal places using String’s indexOf() method:
- Convert
Doubleto StringdoubleStrusingDouble.toString(). - Find index of dot(.) to find number of integer places.
- Get number of decimal places using
doubleStr.length() - integer places -1.
package org.arpit.java2blog;
public class CountNumberOfDecimalPlacesMain {
public static void main(String[] args) {
Double d= 122.434548;
String doubleStr = Double.toString(Math.abs(d));
int integerPlaces = doubleStr.indexOf(".");
int decimalPlaces = doubleStr.length() - integerPlaces -1;
System.out.println("Number of decimal places in 122.434548: "+decimalPlaces);
}
}
Output
Number of decimal places in 122.434548: 6
That’s all about how to count number of decimal places in java/