Search code examples
javascriptjquerystring-formatting

Javascript: why does this produce and ugly string??? I would like currency


var total = 0;
$(".amount").each(function () {
    var value = $(this).val();
    value = (value.length < 1) ? 0 : value;
    var tmp = parseFloat(value).toFixed(2);
    total += tmp;
});
$(".total").text(total);

I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?


Solution

  • .toFixed converts the object from a Number to a String.

    Leave the full values in place and only convert using .toFixed at the very end

    $(".total").text(total.toFixed(2));
    

    Alternatively, convert the string back to a number.

    total = total + + tmp;