javascript 如何使用循环在javascript中将数字增加0.01?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19290628/
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-27 15:01:25  来源:igfitidea点击:

How to increment number by 0.01 in javascript using a loop?

javascriptmathfor-loopfloating-point

提问by hitautodestruct

Problem

问题

I was trying to build out a list of heights in the console by meteres starting from 1.20m and ending up at 2.50m.

我试图在控制台中以米为单位建立一个高度列表,从 1.20m 开始到 2.50m。

I used this code:

我使用了这个代码:

var heights = [];
for ( var i=1.20, l=2.5; i<l; i+=0.01 ){

    heights.push(i);

}

heights = heights.join('\n');

If I console.log( heights )I get:

如果console.log( heights )我得到:

1.2
1.21
1.22
1.23
...

But then at 1.37 I start getting:

但是在 1.37 我开始得到:

1.37
1.3800000000000001
1.3900000000000001
1.4000000000000001
1.4100000000000001
1.4200000000000002
1.4300000000000002

Questions

问题

  • What's going on?
  • How do I fix it?
  • 这是怎么回事?
  • 我如何解决它?

Demo

演示

Here's a demoif you're too lazy to type it in your console :-)

a demo如果您懒得在控制台中输入它,请在此处输入 :-)

采纳答案by George Reith

You are doing this fine. The problem is with the inaccuracy of floating point numbers.

你做得很好。问题在于浮点数的不准确。

Why are floating point numbers so inaccurate?

为什么浮点数如此不准确?

If you wish to display this number then use:

如果您希望显示此数字,请使用:

heights[i].toFixed(2);

Note that toFixed()returns a string and you will have to convert back to a float (parseFloat()) if you want to perform more numerical operations.

请注意,toFixed()返回一个字符串,parseFloat()如果要执行更多数值运算,则必须将其转换回浮点数 ( )。

回答by phenomnomnominal

This is just because of how math works in JavaScript, you can find lots of answers explaining about it - like thisone. The easiest solution is to just do everything times 100, and then divide when adding to the array e.g.

这只是因为数学在 JavaScript 中的工作方式,您可以找到很多解释它的答案 - 就像这个。最简单的解决方案是将所有内容都乘以 100,然后在添加到数组时进行除法,例如

var heights = [], i, l;
for (i = 120; i < 250; i += 1){    
    heights.push(i / 100);    
}

You could use toFixedbut that will give you a Stringas the result.

你可以使用,toFixed但这会给你一个String结果。

回答by Ja?ck

This is due to how floating point numbers are stored internally, it's not JavaScript specific. You can use .toFixed()to store a string representation of the number with the desired accuracy, so:

这是由于浮点数是如何在内部存储的,它不是 JavaScript 特定的。您可以使用.toFixed()以所需精度存储数字的字符串表示形式,因此:

heights.push(i.toFixed(2));

If you want to avoid storing strings and then converting them back into an actual number, you can multiply the step so that it becomes a whole number and then store a division instead:

如果您想避免存储字符串然后将它们转换回实际数字,您可以将步骤乘以使其成为一个整数,然后存储一个除法:

for (var i = 120; i <= 250; ++i) {
    heights.push(i / 100);
}

The difference besides the fact that you now have numbers is that multiple of 0.1are represented in single accuracy, e.g. 2.4instead of "2.40".

除了您现在拥有数字这一事实之外的不同之处在于, 的倍数0.1以单一精度表示,例如,2.4而不是"2.40"

回答by Red Alert

This is because machines use base 2, and you are using base 10 numbers that cannot be accurately represented in base 2 with a floating point number.

这是因为机器使用基数 2,而您使用的基数为 10 的数字无法用浮点数以基数 2 准确表示。

You can use this library to format it: https://github.com/dtrebbien/BigDecimal.js

您可以使用此库对其进行格式化:https: //github.com/dtrebbien/BigDecimal.js

回答by Vadym Tyemirov

As it has been mentioned, toFixed()returns String, and parseFloat()converts Stringto Float. parseFloat()also removes trailing zeros, which makes sense, but was not working for my use case.

如前所述,toFixed()返回StringparseFloat()转换StringFloatparseFloat()还删除尾随零,这是有道理的,但不适用于我的用例。

Here is an example of iteration using Floatand retaining trailing zeroes.

这是使用Float和保留尾随零的迭代示例。

var i = 0.9,
  floats = [];

while (i < 2) {
  i = (i + 0.1).toFixed(1);
  floats.push(i);
  i = parseFloat(i);
}
console.log(floats);


[ '1.0',
  '1.1',
  '1.2',
  '1.3',
  '1.4',
  '1.5',
  '1.6',
  '1.7',
  '1.8',
  '1.9',
  '2.0' ]

If trailing zeroes are not needed, the loop can be simplified as:

如果不需要尾随零,则循环可以简化为:

while (i < 2) {
  floats.push(i);
  i = parseFloat((i + 0.1).toFixed(1));
}

回答by mcamier

Use the method toFixed(float), to limit the amount of digit after comma

使用toFixed(float)方法,限制逗号后的位数

heights.push(i.toFixed(2));