toFixed() 方法不在 javascript 中的 number() 方法内?
toFixed() method working isn't inside number() method in javascript?
我要的是:计算后的结果应该是2位小数。
这是我的代码
let totalNetWeightLocal = 0;
totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));
问题: 计算正常但 toFixed() 不工作。我得到的结果超过 2 个小数。
有人可以帮帮我吗?
您的代码存在问题,.toFixed(2)
位置错误
您的代码所做的类似于
const fullWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal = totalNetWeightLocal + fullWeight.toFixed(2));
这意味着,您将两个字符串加在一起,例如 0 + '10.24'
,这将是 010.24
。您需要做的是:
// you don’t need Number() here:
const itemWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal += itemWeight;
totalNetWeightLocal.toFixed(2);
考虑到,您可能有一个项目列表,您可以编写如下函数:
const items = [
{ netWeight: '4.53', quantity: '3' },
{ netWeight: '20.33', quantity: '10' }
];
const getTotalNetWeightLoal = items => {
const totalNetWeightLocal = items.reduce(
(weight, { netWeight, quantity }) =>
weight + parseFloat(netWeight) * parseInt(quantity),
0
);
return totalNetWeightLocal.toFixed(2);
};
console.log(getTotalNetWeightLoal(items));
试试这个代码。您的代码工作正常。
let item = { "netWeight": "5.99498", "quantity": '8' }
let totalNetWeightLocal = 0;
totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));
console.log(totalNetWeightLocal) // output: 47.96
//Can you provide cases where it failed?
我要的是:计算后的结果应该是2位小数。
这是我的代码
let totalNetWeightLocal = 0;
totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));
问题: 计算正常但 toFixed() 不工作。我得到的结果超过 2 个小数。
有人可以帮帮我吗?
您的代码存在问题,.toFixed(2)
位置错误
您的代码所做的类似于
const fullWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal = totalNetWeightLocal + fullWeight.toFixed(2));
这意味着,您将两个字符串加在一起,例如 0 + '10.24'
,这将是 010.24
。您需要做的是:
// you don’t need Number() here:
const itemWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal += itemWeight;
totalNetWeightLocal.toFixed(2);
考虑到,您可能有一个项目列表,您可以编写如下函数:
const items = [
{ netWeight: '4.53', quantity: '3' },
{ netWeight: '20.33', quantity: '10' }
];
const getTotalNetWeightLoal = items => {
const totalNetWeightLocal = items.reduce(
(weight, { netWeight, quantity }) =>
weight + parseFloat(netWeight) * parseInt(quantity),
0
);
return totalNetWeightLocal.toFixed(2);
};
console.log(getTotalNetWeightLoal(items));
试试这个代码。您的代码工作正常。
let item = { "netWeight": "5.99498", "quantity": '8' }
let totalNetWeightLocal = 0;
totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));
console.log(totalNetWeightLocal) // output: 47.96
//Can you provide cases where it failed?