use*_*754 5 javascript arrays decimal
我正在尝试添加以下内容但它保持连接并返回一个字符串.
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += parseFloat(i).toFixed(2);
});
Run Code Online (Sandbox Code Playgroud)
是的,我需要它返回/添加小数.不确定该怎么做
如果您想要更实用的方法,您还可以使用Array.reduce:
var nums = [1.99, 5.11, 2.99];
var sum = nums.reduce(function(prev, cur) {
return prev + cur;
}, 0);
Run Code Online (Sandbox Code Playgroud)
最后一个参数0是可选的起始值.
如果您不存储浮点数字符串,则不需要使用 parseFloat(i),它可以从字符串中解析浮点数。您可以将其重写为:
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += i;
});
var fixed = total.toFixed(2);
console.log(fixed);
Run Code Online (Sandbox Code Playgroud)
或者
var nums = [1.99, 5.11, 2.99];
var total = 0;
for(var i = 0; i < nums.length; i++){
total += nums[i];
}
var fixed = total.toFixed(2);
console.log(fixed);
Run Code Online (Sandbox Code Playgroud)