0

Here is the code:

function updateCartSubtotal() {
    var subtotal = 0.00;
    $('span.item-subtotal-value').each(function () {
        subtotal = subtotal + parseFloat($(this).text()); //24.00 for example.
    });

    console.log(subtotal); // Logs: "144"
    $('span.cart-subtotal-value').text(subtotal); //Places: "144" in the .text().
    $('span.cart-subtotal').text(subtotal);
}

So what am I doing wrong? Why is this ignoring the two trailing zeroes?

It's adding correctly, just not showing the decimals.

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257

2 Answers2

3

123 and 123.00 are the same. When displaying a float there is no reason to display unnecessary digits.

More important, floats are not specific to currencies - so if decimal digits would be displayed, there would have to be many more.

If you want to display the number with a certain number of digits, use subtotal.toFixed(2). It gives you a string with the correct amount of decimal digits:

>>> 123.00
123
>>> (123.00).toFixed(2)
"123.00"

So your code could look like this:

$('span.cart-subtotal-value, span.cart-subtotal').text(subtotal.toFixed(2));
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

You might be interested in the number_format function from PHPJS, as this will also include thousand separators that are commonly found in currencies.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Why not use something [already available](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed) in JavaScript? When thousand separators are needed/wanted, you are right though - then the function you linked is a good idea. – ThiefMaster Jan 09 '12 at 03:01