3

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!

Ivan
  • 7,770
  • 2
  • 17
  • 25
RoiboisTx
  • 33
  • 5

3 Answers3

1

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.");
        }
    }
}
Omari Celestine
  • 1,272
  • 1
  • 9
  • 18
0

4.9 or 4.90 as a double are both represented by the same approximation. There is no difference between them.

You can, of course, do what you want using String processing on the input. However, you may find BigDecimal a better data type for what you are doing. It distinguishes between 4.9 and 4.90, and can represent each of them exactly.

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    System.out.println(new BigDecimal(4.9));
    System.out.println(new BigDecimal(4.90));
    BigDecimal x1 = new BigDecimal("4.9");
    System.out.println(x1);
    System.out.println(x1.scale());
    BigDecimal x2 = new BigDecimal("4.90");
    System.out.println(x2);
    System.out.println(x2.scale());
  }
}

Output:

4.9000000000000003552713678800500929355621337890625
4.9000000000000003552713678800500929355621337890625
4.9
1
4.90
2
Patricia Shanahan
  • 24,883
  • 2
  • 34
  • 68
0

Omari, I adjusted your code like this and it worked, thanks!

if(result[0].length() == 0 ){

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

    } catch (NumberFormatException e) {

        System.out.println("The entered value is not a decimal number.");

    }catch (ArrayIndexOutOfBoundsException e) {
System.out.print("Error Message" );     
      }
RoiboisTx
  • 33
  • 5