0

I'm using jQuery's .each() and grabbing some numbers. I'm doing some math with those numbers and I'm trying to add the result, but instead of adding it's concatenating. Here's my code so far:

if (zName == 'Premium') {
    $('.product-total .productitemcell .productitemcell').each(function (index, value) {
        oPrice = parseFloat($(this).text().replace('$', ''));
        nPrice = parseFloat(oPrice - (oPrice * (10 / 100))).toFixed(2);
        subTotal += nPrice;
        $(this).html('<s>$' + oPrice + '</s> <span style="color:#ef0f0f;">$' + nPrice + '</span>');
    });
}
console.log(subTotal);

1 Answer 1

3

The .toFixed() function returns a string, not a number.

(Also, "oPrice", "nPrice", and "subTotal" should be declared with var; perhaps they are in code not shown.)

Converting from the return value of .toFixed() won't necessarily preserve any fraction truncation that's taken place. Doing monetary math with JavaScript floating-point math is tricky and error-prone.

Sign up to request clarification or add additional context in comments.

3 Comments

They are declared elsewhere. So i tried doing subtotal+=parseFloat(nPrice); but now i'm getting a Nan error.
@Damien make sure that you initialize "subTotal" to zero somewhere.
Awesome! What's funny is that at one point i did initialize it to zero but that didn't work so i moved on. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.