Home > front end >  Math.round() giving unexpected value
Math.round() giving unexpected value

Time:04-13

I'm trying to round a String value using Math.round as so:

String numberString = "61867345124";
int value = Math.round(Float.parseFloat(numberString)); 

but I'm getting value = 2147483647, what is going on here?

CodePudding user response:

Actually, you have two issues here,

First, the output is 2147483647 because that is the max value an integer can store in Java. And your number is larger than that. You can confirm the max value for a primitive type by calling MAX_VALUE against its wrapper class, like below,

System.out.println(Integer.MAX_VALUE);

If the return value of Math.round is larger than Integer.MAX_VALUE it will return an integer having maximum value it can store,

From the documentation here,

If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

To resolve that you can store the result in a long typed variable.

Second, that will still not get you desired results because Math.round if provided with a float input will return an integer. You need it to return a long instead which is returned if you provide it a double value.

Here are the definitions, from the documentation of Math class.

static int  round(float a)
static long round(double a)

To sum up you need to both store the output as a long as well as you need to parse the string value as double, like below,

String numberString = "61867345124";
long value = Math.round(Double.parseDouble(numberString));
System.out.println(value);

CodePudding user response:

Looks like you are using a number way larger than an integer can contain, so the output is defaulting to the maximum integer value of 2147483647. You probably want to use a long to store that value.

  • Related