Pregunta

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.

¿Fue útil?

Solución

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));

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top