toFixed javascript函数给出奇怪的结果? [英] toFixed javascript function giving strange results?

查看:105
本文介绍了toFixed javascript函数给出奇怪的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字修改为小数点后的2位数,并且我正在使用 toFixed 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.

感谢您的帮助。

推荐答案

这就是浮点数学的工作原理。值19.995不是精确二进制(基数2)。为了更清楚,在划分10/3时想一个确切的数字。

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.

有关更深入的解释,请阅读: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg。 html

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);

或者定义这样的函数(在2分钟内完成,只是一个例子):

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

这篇关于toFixed javascript函数给出奇怪的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆