简体   繁体   English

toFixed() 方法工作不在 javascript 中的 number() 方法内?

[英]toFixed() method working isn't inside number() method in javascript?

What I want: after calculation result should be in 2 decimal format.我想要的是:计算后的结果应该是 2 位十进制格式。

here's my code这是我的代码

let totalNetWeightLocal = 0;

totalNetWeightLocal = totalNetWeightLocal + Number((parseFloat(item.netWeight) * parseInt(item.quantity)).toFixed(2));

Problem: calculation is working but toFixed() isn't working.问题:计算有效但 toFixed() 无效。 I'm getting results in more than 2 decimal values.我得到的结果超过 2 个十进制值。

Can someone please help me?有人可以帮帮我吗?

The problem with your code is, that the .toFixed(2) is at the wrong position您的代码的问题是.toFixed(2)位于错误的位置

What your code does is something like您的代码所做的类似于

const fullWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal = totalNetWeightLocal + fullWeight.toFixed(2));

Which means, you add two strings together like 0 + '10.24' which will be 010.24 .这意味着,您将两个字符串相加,例如0 + '10.24' ,即010.24 What you need to do is:你需要做的是:

// you don’t need Number() here:
const itemWeight = parseFloat(item.netWeight) * parseInt(item.quantity)
totalNetWeightLocal += itemWeight;
totalNetWeightLocal.toFixed(2);

Considering, you might have a list of items you can write a functions as follows:考虑到,您可能有一个可以编写函数的项目列表,如下所示:

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));

Try this code.试试这个代码。 Your code's working fine.您的代码运行良好。

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?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM