Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...