Count Number of Decimal Places in Java

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 to String using Double.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

Using String’s indexof() method

To count number of decimal places using String’s indexOf() method:

  • Convert Double to String doubleStr using Double.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/

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.