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?
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?
Share Improve this question edited Jan 30, 2020 at 4:52 ankitkanojia 3,1224 gold badges24 silver badges37 bronze badges asked Jul 31, 2009 at 18:48 HcabnettekHcabnettek 12.9k38 gold badges129 silver badges192 bronze badges 2- 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 Commented Jul 31, 2009 at 19:01
- String.prototype.toMoney = function() { return "$ " + this; } var amount = total.toFixed(2).toMoney(); $(".total").text(amount); Sweet!!! Works perfect! – Hcabnettek Commented Jul 31, 2009 at 19:09
3 Answers
Reset to default 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;
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());
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);