Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count digits after decimal including last zero

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!

like image 305
RoiboisTx Avatar asked Jan 27 '26 21:01

RoiboisTx


1 Answers

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.");
        }
    }
}
like image 75
Omari Celestine Avatar answered Jan 30 '26 10:01

Omari Celestine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!