Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Math.round() return 0 for NaN arguments?

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

like image 384
MK. Avatar asked Apr 12 '12 03:04

MK.


People also ask

What is the return value of math round?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

How does math round work in Java?

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.

Does round return an int?

Round(decimal) will always return an integral value, these overloads still cannot return an integer value type.

Does Math round round up or down Java?

The answer is Yes. Java does a round down in case of division of two integer numbers.


1 Answers

Math.round() is defined as (long)Math.floor(a + 0.5d).

  1. If a is NaN, then a+0.5d is NaN.
  2. Math.floor() is delagated to StrictMath.floor() which returns NaN when passed in NaN.
  3. When casting NaN to a long, it returns 0

So ultimately, it comes down to why casting NaN to a long returns 0. This issue has been thoroughly discussed in this question.

like image 55
tskuzzy Avatar answered Sep 22 '22 16:09

tskuzzy