我试图将我的数组中的值舍入到2个小数点.我明白我可以使用math.round但是这对整个数组有用吗?或者我需要编写一个函数来单独舍入每个值.
小智 12
这是使用地图的好时机.
// 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]
Run Code Online (Sandbox Code Playgroud)
太简单!;)
你必须遍历数组。然后,对于每个元素:
<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
Run Code Online (Sandbox Code Playgroud)
循环!
var x = 0;
var len = my_array.length
while(x < len){
my_array[x] = my_array[x].toFixed(2);
x++
}
Run Code Online (Sandbox Code Playgroud)
是的,这里 while 循环更快。
| 归档时间: |
|
| 查看次数: |
14323 次 |
| 最近记录: |