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.

Output

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.

Output

That’s all about how to count number of decimal places in java/

Was this post helpful?

Leave a Reply

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