I thought that result of any mathematical operation on a NaN should give me a NaN back, but Math.round(Float.NaN) == 0
What is the rationale for such behavior of Math.round()?
Curiously, C# behaves differently: http://msdn.microsoft.com/en-us/library/75ks3aby.aspx
round() The Math. round() function returns the value of a number rounded to the nearest integer.
round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0.
Round(decimal) will always return an integral value, these overloads still cannot return an integer value type.
The answer is Yes. Java does a round down in case of division of two integer numbers.
Math.round()
is defined as (long)Math.floor(a + 0.5d)
.
a
is NaN
, then a+0.5d
is NaN
.Math.floor()
is delagated to StrictMath.floor()
which returns NaN
when passed in NaN
.NaN
to a long
, it returns 0So ultimately, it comes down to why casting NaN
to a long
returns 0. This issue has been thoroughly discussed in this question.
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