1

I have the following code that calculates and shows the sum of two values.

var oldprice_formated = parseFloat(oldprice).toFixed(2);
var extraPrice = parseFloat(3).toFixed(2);
  if(initials != '') {
    var new_price = oldprice_formated + extraPrice;
    $('.product-detail .woocommerce-Price-amount.amount').html('<span>€</span>'+new_price);
  } else {
    $('.product-detail .woocommerce-Price amount.amount').html('<span>€</span>'+oldprice_formated);
  }

For example:

oldprice_formated = parseFloat(49.99).toFixed(2);
extraPrice = parseFloat(3.00).toFixed(2)

The expected result: Sum is 52.99

Actual result: Sum is 49.003.00

What am I doing wrong? I assume it's with the number parsing, but not sure what I should change to make it work correctly. Thanks!

Phiter
  • 14,570
  • 14
  • 50
  • 84

2 Answers2

3

.toFixed() returns a string, not a number with only two decimal places.

oldprice_formated = parseFloat(49.99).toFixed(2); // "49.99"
extraPrice = parseFloat(3.00).toFixed(2); // "3.00"

When adding those two variables, instead of a number sum, you're concatenating two strings:

"49.99" + "3.00"; // "49.993.00"

I believe this is what you'll want to do:

var new_price = parseFloat(oldprice_formated) + parseFloat(extraPrice);

Or simply run .toFixed() after you sum those values which were already parsed to floats.

Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Also you don't need to run `parseFloat` on a number. – Phiter Mar 28 '18 at 19:15
  • Hi, thanks for the help! This indeed seems a logical explanation. But when I just use parseFloat(), 49.99 becomes 49 and the sum is 52 instead of 52.99. How can I format the number to 2 decimals? – Senne Vandenputte Mar 28 '18 at 19:17
  • This isn't supposed to happen. `parseFloat(49.99)` will return `49.99`. Are you sure the number you're passing to `parseFloat` is properly formatted? Can you put some examples? – Phiter Mar 28 '18 at 19:18
  • You're right, it was passing 49,99 to `parseFloat` and not 49.99. Thanks a lot for the help! – Senne Vandenputte Mar 28 '18 at 19:24
  • Yeah, javascript doesn't understand `,` as a decimal separator. You can use `replace` if your numbers have this. – Phiter Mar 28 '18 at 19:25
0

Because toFixed() returns a string, the + operator acts as a string concatenator. If you want it to operate as an addition operator, you must typecast your values as numbers:

let oldprice = 49.99;
let oldprice_formatted = parseFloat(oldprice).toFixed(2);
let extraPrice = parseFloat(3).toFixed(2);

console.log(`string concatenation: ${oldprice_formatted + extraPrice}`)
console.log(`type conversion: ${+oldprice_formatted + +extraPrice}`)
BotNet
  • 2,759
  • 2
  • 16
  • 17