1

I have the below requirement:

  1. input String = "1.00000" should be converted to int ( because actually no fraction at all )
  2. input String = "1" should be converted to int 1
  3. however, input String ="1.0001" should be an Exception (because has fraction )

Previously I was assuming Integer.valueOf("1.00000") should return an integer.However it returns NumberFormatException.

any Java library that can solve this, or at least can check if 1.0000 is actually an integer so I can safely parse as Double and cast it to int?

2
  • 3
    1.00000 is never an int. Commented Apr 11, 2019 at 5:03
  • 1
    Who gave you these requirements, and why? Commented Apr 11, 2019 at 5:45

2 Answers 2

4

BigDecimal class

Java itself has a library that does exactly this: BigDecimal

Example:

private static int parse(String input) throws ArithmeticException {
    return new BigDecimal(input).intValueExact();
}

The intValueExact method throws an ArithmeticException if the BigDecimal object has a non-zero fractional part.

Sign up to request clarification or add additional context in comments.

1 Comment

This is really the best answer. I had to delete mine.
1

One way to tackle the problem is, you can use regex to first ensure that the input exactly matches the format of a number with fractional part being optional and if at all then all being zeroes and if yes, then go ahead and parse it else throw Exception or whatever you want to do. Check this Java code,

List<String> list = Arrays.asList("1.00000","1","1.0001");
Pattern intPat = Pattern.compile("(\\d+)(\\.0+)?");

list.forEach(x -> {
    Matcher m = intPat.matcher(x);
    if (m.matches()) {
        int num = Integer.parseInt(m.group(1));
        System.out.println(num);
    } else {
        System.out.println(x +" is not a pure Integer"); // Throw exception or whatever you like
    }
});

Outputs,

1
1
1.0001 is not an Integer

Also, as long as the numbers you are working with are confined within integer range, its all good but to ensure the numbers don't cross integer limit, you may want to use a different quantifier.

Another alternate simpler solution you can go for is, parse the number as double and compare it with its int form and if both are equal then it is a pure integer else not. I'll prefer this than my first solution using regex. Java code,

List<String> list = Arrays.asList("1.00000","1","1.0001");

list.forEach(x -> {
    double num = Double.parseDouble(x);
    if (num == (int)num) {
        System.out.println((int)num);
    } else {
        System.out.println(x + " is not a pure Integer");
    }

Prints,

1
1
1.0001 is not a pure Integer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.