0

How can I convert a string of a number such as "131.40" to the number 131.40, or "14.1" to the number 14.10?

If I use parseFloat, the output leaves out the zero (131.4) and toFixed returns a string. I'm trying to represent USD currency.

Here is the full context of my code:

const products = [{
id: 1,
price: 109.1,
quantity: 1,
title: "T-Shirt"
}, 
{
id: 2,
price: 22.3,
quantity: 1,
title: "Jeans"
}]

 function totalPrice(storageItems){
      const totalPriceHolder = []
      storageItems.map((a, index) => {
        const totalPrice = a.price * a.quantity;
        totalPriceHolder.push((totalPrice))
      })
   console.log("Check1", totalPriceHolder)
       const totalPriceReduce = totalPriceHolder.reduce((a, b) => a + b, 0).toFixed(2);
   console.log("Check 2", totalPriceReduce)
       return parseFloat(totalPriceReduce)
    }

console.log(totalPrice(products))
tadman
  • 208,517
  • 23
  • 234
  • 262
Alex
  • 293
  • 5
  • 21
  • Floating point numbers are displayed without trailing zeroes. If you want those, you need to display with a particular format. The zero isn't "left out", it's there, but internally the number is binary and has a *lot* of trailing zeroes. – tadman Feb 24 '21 at 08:11
  • 1
    Tip: Using floating point values for currency can be tricky, you'll get all kinds of rounding issues if you're not very careful. – tadman Feb 24 '21 at 08:11
  • 1
    You could always store the value as an integer by multiplying it by 100, truncating, and then dividing the value by 100 when you wish to display it. Then 131.40 would be stored as 13140. – Liftoff Feb 24 '21 at 08:12
  • Beware that IEEE-754 double-precision binary floating point (the kind of numbers JavaScript uses for its `number` type) are not generally a good choice for financial calculations. See [this question and its answers](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for details. But if you do what David describes above, you're fine if you're not dealing with very large sums (the precision issue occurs even in whole numbers above 9,007,199,254,740,991). (You can use the new `BigInt` if you might need larger ones.) – T.J. Crowder Feb 24 '21 at 08:15

0 Answers0