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

0

How can I handle this string so that it returns 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 this to me:

    
asked by anonymous 15.10.2014 / 06:10

2 answers

2

There are great answers about the subject in English OS .

You can even format your output using functions like:

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

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

If you want to see why this happens, visit THE FLOATING-POINT GUIDE

    
15.10.2014 / 08:03
0

Make Friends:

$(".subtotal2").text((23.90).toFixed(2));
$(".todo_total").text((sum*12).toFixed(2));
    
22.07.2016 / 04:26