toFixed javascript function giving strange results?

I am trying to fix the number to 2 digits after decimal and for that i am using toFixedfunction of javascript. Below are the strange results i am getting, please check and help me.

var number = 11.995;
number.toFixed(2); // giving me 11.99 which is correct

var number = 19.995;
number.toFixed(2); // giving me 20.00 which is incorrect

Can anyone tell me why it is happening.

Thanks for your help.


Solution 1:

This is how floating point math works. The value 19.995 is not exact binary (base 2). To make it more clear, think of an exact number when you divide 10/3.

For more in-depth explanations, read this: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

In your case you can work with strings instead (at least it seems like that is what you want):

number.toString().substr(0, n);

Or define a function like this (made in 2 minutes, just an example):

Number.toFixed = function(no, n) {
    var spl = no.toString().split('.');
    if ( spl.length > 1 ) {
        return spl[0]+'.'+spl[1].substr(0,n);
    }
    return spl[0];
}

Number.toFixed(19.995, 2); // 19.99

Solution 2:

toFixed rounds the value. Since 19.995 is exactly halfway between 19.99 and 20.00, it has to choose one of them. Traditionally, rounding prefers the even result (this prevents bias, since round-ups and round-downs will be equal).