Javascript 我如何将数字相加并返回小数点后两位?

Javascript 我如何将数字相加并返回小数点后两位?,javascript,numbers,Javascript,Numbers,我正在尝试获取购买物品的总价,但由于所有数字都存储为字符串,因此无法正确添加。我尝试使用Number(price).toFixed(2),但是toFixed()方法以字符串的形式返回数字,因此不能与其他数字相加。你能看一下我的代码,告诉我怎样才能得到它,这样数字才能正确相加吗 findTotal = () => { let currentTotal = 0, { receiptProducts } = this.props if(this.props.expeditedShipping)

我正在尝试获取购买物品的总价,但由于所有数字都存储为字符串,因此无法正确添加。我尝试使用
Number(price).toFixed(2)
,但是
toFixed()
方法以字符串的形式返回数字,因此不能与其他数字相加。你能看一下我的代码,告诉我怎样才能得到它,这样数字才能正确相加吗

findTotal = () => {
let currentTotal = 0, { receiptProducts } = this.props

if(this.props.expeditedShipping){
  receiptProducts.map((product) => {
    currentTotal += Number(product.price)toFixed(2) + Number(product.shippingPrice).toFixed(2)
   })
  return currentTotal
} else {
  receiptProducts.map((product) => {
    currentTotal += Number(product.price).toFixed(2) + Number(product.shippingPrice).toFixed(2)
  })
} return currentTotal
}

你接近了!您只需将字符串解析回数字,然后加法就能正常工作:

findTotal = () => {
let currentTotal = 0, { receiptProducts } = this.props

if(this.props.expeditedShipping){
  receiptProducts.map((product) => {
    currentTotal += parseFloat(Number(product.price).toFixed(2)) + parseFloat(Number(product.shippingPrice).toFixed(2))
   })
  return currentTotal
} else {
  receiptProducts.map((product) => {
    currentTotal += parseFloat(Number(product.price).toFixed(2)) + parseFloat(Number(product.shippingPrice).toFixed(2))
  })
} return currentTotal
}

如果在加法之前四舍五入到两个小数点不是你想要的,你也可以在返回值上使用
.toFixed()
,然后在最后,在总数上删除所有其他
.toFixed())
s并在末尾返回currentTotal.toFixed(2)toFixed是一个字符串,所以您添加的是字符串,而不是数字为什么?转换为数字、返回字符串并再次转换为数字?确保计算中有两个小数点,以防数字的小数位数过多(即2.028),这似乎是询问者所寻找的,否则,如果他们知道自己的数字已经有了2个小数点,那么仅仅添加这些值就可以了。我不知道OP想要什么,但是如果一个价格有超过2个小数点,这通常是有原因的。我并不是因为你的答案没有错而否定你的答案,但我认为这是OP可能想考虑的问题。这是公平的,我在答案末尾的评论也简要说明了这一点。