如何将数组中的所有值四舍五入到小数点后2位

How to round all the values in an array to 2 decimal points

本文关键字:四舍五入 小数点 2位 数组      更新时间:2023-09-26

我正在尝试将数组中的值四舍五入到2个小数点。我知道我可以使用math.round,但这对整个数组有效吗?或者我需要写一个函数来分别对每个值进行四舍五入。

现在是使用地图的好时机。

// 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]

太容易了!)

您必须循环遍历数组。然后,对于每个元素:

  • 如果您希望逗号后面正好有两位数字,请使用<number>.toFixed(2)方法
  • 否则,请使用Math.round(<number>*100)/100

两种方法的比较:

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

循环!

var x = 0;
var len = my_array.length
while(x < len){ 
    my_array[x] = my_array[x].toFixed(2); 
    x++
}

是的,一段时间的循环在这里更快。

您还可以使用ES6语法

var arr = [1.122,3.2252,645.234234];
arr.map(ele => ele.toFixed(2));