Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does rounding -0.1 return -0

Tags:

javascript

While testing, I noticed something strange with Math.round().

When I was rounding negative numbers close to 0 (-0.1, -0.01, etc), the return value in my console would be -0 rather than 0. Even stranger, if I were to set that same value to an element's text, the element would display 0, instead of -0.

DEMO: http://jsfiddle.net/dirtyd77/qcug9/

enter image description here

Can anyone explain why this occurs? Any help would be greatly appreciated!

Also, I am using Chrome Version 33.0.1750.117.

like image 362
Dom Avatar asked Apr 16 '26 15:04

Dom


1 Answers

The kind of numbers JavaScript uses (IEEE-754 double-precision floating point) have the concept of both "positive" and "negative" zero.

The next highest integer to -0.1 is -0. "Highest" in this case means "toward positive infinity."

From the specification, §15.8.2.15 "Math.round":

If x is less than 0 but greater than or equal to -0.5, the result is −0.

-0 and +0 are both rendered as just 0 when converted to string. For instance:

console.log(-0)         // 0 or -0 depending on what console you use
console.log(String(-0)) // 0 (always)
like image 125
T.J. Crowder Avatar answered Apr 18 '26 06:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!