0

Why does -0.5 when being passed on the Math.round results to 0? and 0.5 when being passed also results to 1? shouldn't it be that when you pass -0.5 to Math.round() should also produce -1 as result? I obtained the -1 result when the number was -0.6.

anathema
  • 947
  • 2
  • 15
  • 27

3 Answers3

1

Math.round(double) is documented as:

Returns the closest long to the argument, with ties rounding to positive infinity.

So -0.5 is rounding up (towards positive infinite) instead of down towards negative infinity. It's behaving exactly as documented.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

The working of round( x ) is implemented as floor( x + 0.5 ) until Java6 atleast. So, by that logic, floor(-0.5 + 0.5) gives you 0 and floor(0.5+0.5) gives you 1

You can refer this link for more details

Why does Math.round(0.49999999999999994) return 1

Community
  • 1
  • 1
smaug
  • 846
  • 10
  • 26
0

If you read the docs, it says that round() "returns the closest long to the argument, with ties rounding up."

"Up" is towards positive infinity, not away from 0.

ETA: I see from Jon Skeet's answer that Java 8 docs improved the clarity on this. This answer quotes Java 7, which is bit more confusing than what 8 says.

dcsohl
  • 7,186
  • 1
  • 26
  • 44