如何在JavaScript中使用循环增加数字0.01? [英] How to increment number by 0.01 in javascript using a loop?
问题描述
问题
我试图从1.20米开始,以2.50米为结尾,在控制台上创建一个高度列表。 b
$ b
我用这个代码:
pre $ var heights = []; (i = 1.20,l = 2.5; i <1; i + = 0.01){
heights.push(i);
。
}
heights = heights.join('\\\
');
如果我 console.log(heights)
我得到:
1.2
1.21
1.22
1.23
...
但是在1.37我开始得到:
1.37
1.3800000000000001
1.3900000000000001
1.4000000000000001
1.4100000000000001
1.4200000000000002
1.4300000000000002
$ c
$ b 问题
- 发生什么事了? li>
- 如何解决这个问题?
Demo
这是 演示 如果你太懒惰在你的控制台中输入: - )
解决方案问题在于浮点数的不准确。
为什么浮点数不准确?如果你想显示这个数字,那么使用:
heights [i] .toFixed(2);
注意 toFixed()
返回一个字符串如果你想执行更多的数字操作,你必须转换回浮动( parseFloat()
)。
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.
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:
1.2
1.21
1.22
1.23
...
But then at 1.37 I start getting:
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 demo if you're too lazy to type it in your console :-)
解决方案 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.
这篇关于如何在JavaScript中使用循环增加数字0.01?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!