javascript 如何将数组中的所有值四舍五入为 2 个小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9671203/
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
How to round all the values in an array to 2 decimal points
提问by kishan patel
I am trying to round the values in my array to 2 decimal points. I understand i can use math.round but will that work for an whole array? Or will i need to write a function to round each value individually.
我试图将数组中的值四舍五入到 2 个小数点。我知道我可以使用 math.round 但这对整个数组有效吗?或者我是否需要编写一个函数来单独舍入每个值。
采纳答案by tkone
Loops!
循环!
var x = 0;
var len = my_array.length
while(x < len){
my_array[x] = my_array[x].toFixed(2);
x++
}
And, yes, a while loop is faster here.
而且,是的,这里的 while 循环更快。
回答by Richard Morgan
This is a great time to use map.
这是使用地图的好时机。
// first, let's create a sample array
var sampleArray= [50.2334562, 19.126765, 34.0116677];
// now use map on an inline function expression to replace each element
// we'll convert each element to a string with toFixed()
// and then back to a number with Number()
sampleArray = sampleArray.map(function(each_element){
return Number(each_element.toFixed(2));
});
// and finally, we will print our new array to the console
console.log(sampleArray);
// output:
[50.23, 19.13, 34.01]
So easy! ;)
太简单!;)
回答by Rob W
You have to loop through the array. Then, for each element:
你必须遍历数组。然后,对于每个元素:
- If you want exactely two digits after the comma, use the
<number>.toFixed(2)
method. - Otherwise, use
Math.round(<number>*100)/100
.
- 如果您想在逗号后恰好有两个数字,请使用该
<number>.toFixed(2)
方法。 - 否则,使用
Math.round(<number>*100)/100
.
Comparison of both methods:
两种方法的比较:
Input .toFixed(2) Math.round(Input*100)/100
1.00 "1.00" 1
1.0 "1.00" 1
1 "1.00" 1
0 "0.00" 0
0.1 "0.10" 0.1
0.01 "0.01" 0.01
0.001 "0.00" 0