Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java's Math.round() cannot handle this number?

Tags:

java

rounding

I have code like this:

System.out.println("Math.round(1423562400L) => " + Math.round(1423562400L));

And the result is this:

Math.round(1423562400L) => 1423562368

This value is a 64-bit integer but it easily fits inside a 32-bit integer which should fit in a double. What is going on?

like image 676
swdev Avatar asked May 17 '16 03:05

swdev


People also ask

How do you stop rounding errors in Java?

To avoid the floating-point rounding issue in a precise calculation like currency, Java has introduced a BigDecimal class. We can use BigDecimal instead of float or double. Arithmetic, comparison, hashing, rounding, manipulation, and format conversion are all supported by this class.

How does Math round work in Java?

Java Math round() The round() method rounds the specified value to the closest int or long value and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.

How do you round a number in Java?

The Math. round() method in Java is used to round a number to its​ closest integer. This is done by adding 1 / 2 1/2 1/2 to the number, taking the floor of the result, and casting the result to an integer data type.

Does Java round 0.5 up or down?

It is used for rounding a decimal to the nearest integer. In mathematics, if the fractional part of the argument is greater than 0.5, it is rounded to the next highest integer. If it is less than 0.5, the argument is rounded to the next lowest integer.


1 Answers

According to the JLS,

15.12.2.5. Choosing the Most Specific Method

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

It follows that Math.round(float) is more specific than Math.round(double), and since they're both valid overloads, the compiler chooses the former, resulting in lost data.

To correct your output, simply change 1423562400L to 1423562400d.

like image 165
shmosel Avatar answered Sep 22 '22 12:09

shmosel