How to return 2 decimals in a monetary value with jQuery?

Asked

Viewed 137 times

0

How can I treat this string to return only 2 decimals after the point?

$(".subtotal2").text(23.90);
    var sum = 0;
    $(".subtotal2").each(function() {

        var val = $.trim( $(this).text() );
        if (val) { val = parseFloat( val.replace( /^\$/, "" ) ); sum += !isNaN( val ) ? val : 0; }

});
$(".todo_total").text(sum*12);

This code for now returns me this:

inserir a descrição da imagem aqui

  • Do not use float to represent money in Javascript, if possible. Use integer values representing the smallest possible unit (cents).

  • Related: http://answall.com/questions/11018/como-representa-dinheiro-em-javascript & also: http://answall.com/questions/14728/performs%C3%A7%C3%A3o-de-floating-point-beads-javascript-with-precis%C3%A3o-absolute

2 answers

2

There are great answers on the subject in the English SO.

You can even format your output using functions like:

toFixed(2);
toPrecision(12);
sprintf("%.2f", number);
round(number, 12);

However, as @mgibsonbr has already commented, the best thing to do is to use integers.

If you want to consult why this happens, go to THE FLOATING-POINT GUIDE

0

Do so friend:

$(".subtotal2").text((23.90).toFixed(2));
$(".todo_total").text((sum*12).toFixed(2));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.