Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将数组中的所有值舍入为2个小数点_Javascript_Html - Fatal编程技术网

Javascript 如何将数组中的所有值舍入为2个小数点

Javascript 如何将数组中的所有值舍入为2个小数点,javascript,html,Javascript,Html,我试图将数组中的值四舍五入到2个小数点。我知道我可以使用math.round,但这对整个数组有效吗?或者我需要编写一个函数来分别对每个值进行四舍五入 您必须在数组中循环。然后,对于每个元素: 如果您希望逗号后面有两位数字,请使用该方法 否则,请使用 两种方法的比较: Input .toFixed(2) Math.round(Input*100)/100 1.00 "1.00" 1 1.0 "1.00" 1 1 "1.00"

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

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

  • 如果您希望逗号后面有两位数字,请使用该方法
  • 否则,请使用
两种方法的比较:

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
而(x

是的,while循环在这里更快。

这是使用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]

太容易了!;)

您还可以使用ES6语法

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

如果您想为数组中的每个元素指定两个小数点,可以为每个元素调用Math.Round方法,或者您正在寻找其他方法。成功了。我只是想知道,为什么这里的while循环更快?我坐在一位计算机逻辑天才旁边,他坚信for循环会更快?我有点搞混了,你最好删除
x
并执行
,而(len--){my_数组[len]=my_数组[len]。toFixed(2);}
我的答案中的方法比这篇评论中的方法慢1毫秒。。。请参阅:尽管
while
循环仍比
for
循环快。但是就像Knuth说的。。。“我们应该忘记小效率,比如说97%的时间:过早优化是万恶之源”当心
。toFixed()
方法是向我的数组返回字符串。如果希望它返回一个浮点值,请使用
parseFloat(my_array[x]).toFixed(2)解析它+1到Kengham的评论。给定的答案会将所有元素转换为字符串,这些字符串可能会产生意外的后果。干得好,这就是我要找的。请小心,正如Kegman指出的,.toFixed()方法正在返回字符串。
// 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]