Count digits after decimal including last zero

RoiboisTx :

I have this,

import java.util.Scanner;

public class StringDecimalPartLength {

    public static void main(String[] args){
       Scanner input = new Scanner(System.in);
       System.out.print("Enter a decimal number: ");
       Double string_Temp = Double.parseDouble(input.nextLine().replace(',', '.'));
       String string_temp = Double.toString(string_Temp);
       String[] result = string_temp.split("\\.");
       System.out.print(result[1].length() + " decimal place(s)");
    }
}

it works until I enter a number with trailing zero, such as 4,90. It ignores the zero and returns 1.

How to fix this? Thank you!

Omari Celestine :

Since you are already reading the input as a string, you can save that value and then test to see if it is a valid decimal number:

import java.util.Scanner;

public class StringDecimalPartLength {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        String value = input.nextLine().replace(',', '.');

        try {
            Double.parseDouble(value);

            String[] result = value.split("\\.");

            System.out.print(result[1].length() + " decimal place(s)");
        } catch (NumberFormatException e) {
            System.out.println("The entered value is not a decimal number.");
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105772&siteId=1