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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With