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

ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
Hcabnettek
  • 12,678
  • 38
  • 124
  • 190
  • what i tend to do is always do maths as floats or ints, keeping the sources as they are for any future operations. I then have a prototype coded .money(currencySign) which is used purely for display of results to end user but not in any math operations--outputs a string. – Dimitar Christoff Jul 31 '09 at 19:01
  • String.prototype.toMoney = function() { return "$ " + this; } var amount = total.toFixed(2).toMoney(); $(".total").text(amount); Sweet!!! Works perfect! – Hcabnettek Jul 31 '09 at 19:09

3 Answers3

13

.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;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • ++ saved me, I was applying `.toFixed(2)` to float but that converted it to string and when adding with one `+` I got 5+5=55 instead of 5+5=10. :) Thank you. – rmagnum2002 Jun 30 '16 at 20:28
1

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());
dcharles
  • 4,822
  • 2
  • 32
  • 29
0

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
  • 304
  • 1
  • 5