javascript toFixed(2) 函数不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13999570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:27:00  来源:igfitidea点击:

toFixed(2) function not working

javascriptjquery

提问by Rahul Desai

This one is weird, because I got it running in this fiddlebut it is not working in the main fiddle. I believe the code is the same.

这个很奇怪,因为我让它在这个 fiddle 中运行,但它在main fiddle 中不起作用。我相信代码是一样的。

Here is the main function:

这是主要功能:

window.setInterval(function(){
    for(var i=0; i < companies.length; i++) {
        var randomVal = (Math.random()*(10 - (-10) + 1)) + (-10);
        randomVal = randomVal / 100;
        randomVal = Number(randomVal.toFixed(2));
        companies[i].price += randomVal;
        //companies[i].price = companies[i].price.toFixed(2);
        $('#price'+i).html(companies[i].price);
    }
}, 1000);

A value like 34.569999999999986isnt been cut down to 34.56. Any idea what is wrong?

像这样的值34.569999999999986没有被削减到34.56. 知道出了什么问题吗?

回答by Nathan Wall

This has to do with a common problem that occurs when converting between binary floating point values and decimal representations. See this fiddle, which is like your "working" one, but I altered the pricevalue so that it also breaks.

这与在二进制浮点值和十进制表示之间转换时发生的常见问题有关。看这个 fiddle,它就像你的“工作”,但我改变了这个price值,所以它也坏了。

Here's an even simpler demo that gets right to the heart of the problem: http://jsfiddle.net/2NHSM/4/

这是一个更简单的演示,它直接解决了问题的核心:http: //jsfiddle.net/2NHSM/4/

As you can see, the output of 1.23 - 1is 0.22999999999999998. That's obviously off by a little bit, but it has to do with the way computers represent numbers.

如您所见,输出1.23 - 10.22999999999999998。这显然有点偏差,但这与计算机表示数字的方式有关。

Computers hold numbers as binary digits. 1.23is actually a "repeating decimal" in binary (just like 1/7 is repeating in decimal), so there's no 100% accurate way to store it. As a result, when you subtract 1.23 - 1you get an answer that is slightly off because 1.23was never accurate to begin with.

计算机将数字保存为二进制数字。1.23实际上是二进制的“重复十进制”(就像 1/7 在十进制中重复一样),所以没有 100% 准确的方法来存储它。结果,当您减去时,您1.23 - 1会得到一个稍微偏离的答案,因为1.23一开始就永远不准确。

The same thing is happening in your case. To fix it, just use toFixedright before you display the value, not before you add something else to it.

在你的情况下也发生了同样的事情。要修复它,只需toFixed在显示值之前使用,而不是在向其添加其他内容之前使用。



Update

更新

Here's a working fiddle: http://jsfiddle.net/2NHSM/6/

这是一个工作小提琴:http: //jsfiddle.net/2NHSM/6/



Update 2

更新 2

Also note that toFixedcan have unexpected rounding behavior. Try the following in the console:

另请注意,toFixed可能会有意外的舍入行为。在控制台中尝试以下操作:

1.35.toFixed(1);
// => 1.4
1.45.toFixed(1);
// => 1.4

You might want to use Math.roundinstead.

您可能想Math.round改用。

Math.round(1.35 * 10) / 10
// => 1.4
Math.round(1.45 * 10) / 10
// => 1.5

回答by sachleen

Floating points are approximations so when you add, they don't always end up clean numbers. Just call toFixed when you display it:

浮点数是近似值,因此当您添加时,它们并不总是以干净的数字结束。显示时调用 toFixed 即可:

companies[i].price += randomVal;
$('#price'+i).html(companies[i].price.toFixed(2));

Demo

演示



This is why your //companies[i].price = companies[i].price.toFixed(2);didn't work:

这就是你//companies[i].price = companies[i].price.toFixed(2);没有工作的原因:

toFixed()returns a string, so after the first call, companies[i].priceis a string. When you do companies[i].price += randomVal;, it is doing string concatenation instead of numeric addition. It'll produce something like:

toFixed()返回一个字符串,所以在第一次调用之后,companies[i].price是一个字符串。当您这样做时companies[i].price += randomVal;,它正在执行字符串连接而不是数字加法。它会产生类似的东西:

577.05
577.050.05
577.050.050.1

So you can't call toFixed on it anymore because:

所以你不能再调用 toFixed 了,因为:

  1. It's a string
  2. It's not even a valid number
  1. 这是一个字符串
  2. 它甚至不是一个有效的数字

So, how would you fix that? Convert it to a number by multiplying by 1 (or Number());

那么,你会如何解决这个问题?通过乘以 1(或Number())将其转换为数字;

companies[i].price += randomVal;
companies[i].price = companies[i].price.toFixed(2)*1;
$('#price'+i).html(companies[i].price);

Demo

演示

With either of these solutions, the first call to toFixed()is unnecessary.

对于这两种解决方案中的任何一种,toFixed()都不需要第一次调用。

回答by Ja?ck

That's because after applying .toFixed()you're adding the value to another variable, which then causes the precision to go haywire again.

那是因为在应用之后,.toFixed()您将值添加到另一个变量,然后导致精度再次失控。

Instead use this for displaying:

而是使用它来显示:

$('#price'+i).html(companies[i].price.toFixed(2));

回答by jremmen

The reason it works in your first example is because you are resetting the value of price to 577 on each pass.

它在您的第一个示例中起作用的原因是因为您在每次传递时都将 price 的值重置为 577。

Try this, it calls .toFixed(2) on the price after the sum has been calculated and also returns it back to your variable.

试试这个,它在计算总和后对价格调用 .toFixed(2) 并将其返回给您的变量。

You can probably ditch the first .toFixed thats called on randomVal.

您可能可以放弃在 randomVal 上调用的第一个 .toFixed。

 window.setInterval(function(){
    for(var i=0; i < companies.length; i++) {
        var randomVal = (Math.random()*(10 - (-10) + 1)) + (-10);
        randomVal = randomVal / 100;
        randomVal = Number(randomVal.toFixed(2));
        companies[i].price += randomVal;
        companies[i].price = Number(companies[i].price.toFixed(2)); 
        $('#price'+i).html(companies[i].price);
    }
}, 1000);

回答by KARTHIKEYAN.A

your conversion data is response[25] and follow the below steps.

您的转化数据是 response[25] 并按照以下步骤操作。

var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34