如何将数组中的所有值四舍五入到小数点后2位
How to round all the values in an array to 2 decimal points
我正在尝试将数组中的值四舍五入到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));
相关文章:
- 将数字四舍五入到小数点后两位
- 将数字四舍五入到小数点后两位,以设置货币格式
- AngularJS {{ val | number:1 }} 不四舍五入到小数点后 1 位
- 小数点后两位四舍五入-找不到正确的公式
- 我怎样才能对浮点数进行四舍五入,使小数点后只有两个尾随数字
- 在 Javascript 中难以将 json 对象值四舍五入到小数点后两位
- 如何将数组中的所有值四舍五入到小数点后2位
- 如何将减去的值四舍五入到小数点后两位
- Javascript四舍五入到最接近的小数点后2位(但向下五舍五入)
- JavaScript在内联样式属性上四舍五入到小数点后1位
- 将数字四舍五入到小数点后2位
- 将小数点后第三位四舍五入到最接近的5位
- 在javascript/jquery中四舍五入到小数点后3位
- 将每个文本框四舍五入到小数点后2位
- 怎么四舍五入到小数点后2位
- javascript中四舍五入到小数点后2位
- JavaScript数学,在Jquery模板中四舍五入到小数点后两位
- JS四舍五入到小数点后两位
- javascript数学,以.05为增量四舍五入到小数点后两位
- 如何在Javascript中四舍五入小数点后两位