views:

159

answers:

3
 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?

Thanks, ~ck in San Diego

+5  A: 

.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;
David Dorward
+1  A: 

Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation

Using that plugin may also indirectly solve your issue.

It's usage would reduce your script to:

$('.total').text($('.amount').sum());
Marve
A: 

You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added.

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