Can anyone tell me why it is happening.
The IEEE-754 double-precision binary floating point number standard used by JavaScript's number
type (and similar times in several other languages) does not perfectly store all numbers, it stores some numbers imprecisely, in a way that lets it A) Store them in just 64 bits, and B) Calculate with them quickly.
For 11.995
, the actual value is 11.99499988555908203125
, just slightly less than 11.995
.
For 19.995
, the actual value is 19.9950008392333984375
, just slightly more than 19.995
.
That explains why when you round them using the usual round-to-nearest-half-up operation, 11.995
(which is really 11.99499988555908203125
) rounds down to 11.99
but 19.995
(which is really 19.9950008392333984375
) rounds up to 20.00
.
(This site has a handy calculator for visualizing this stuff.)
More here on SO: