Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toFixed javascript function giving strange results?

Tags:

javascript

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.

like image 753
Ravinder Singh Avatar asked Feb 20 '23 09:02

Ravinder Singh


1 Answers

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
like image 116
David Hellsing Avatar answered Mar 02 '23 21:03

David Hellsing