Table of Contents
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
Double
toString
usingDouble.toString()
. - Split the String by dot(.) and assign it to String array
strArr
. - Get number of decimal places using
strArr[1].length
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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
1 2 3 |
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
Double
to StringdoubleStr
usingDouble.toString()
. - Find index of dot(.) to find number of integer places.
- Get number of decimal places using
doubleStr.length() - integer places -1
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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
1 2 3 |
Number of decimal places in 122.434548: 6 |
That’s all about how to count number of decimal places in java/
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.