Reputation: 331
I have a javascript function with this code
total = parseFloat(subtotal).toFixed(2);
if(!$('#tablebody').is(':empty')){
$('#tablebody tr').each(function() {
total += parseFloat($(this).find('.subtotals').html()).toFixed(2);
});
}
But it isn't doing arithmetic operations instead it is giving me an output something like this 251.562500000.00250.00
. It just concatenates the numbers
What am I doing wrong?
Upvotes: 2
Views: 69
Reputation: 1164
The toFixed function is converting them to string. Strings behave by concatenating when encountering addition operators. http://www.w3schools.com/jsref/jsref_tofixed.asp
Upvotes: 0
Reputation: 48247
toFixed
returns a string, defeating your parseFloat
call. Since total
is already a string, the runtime has no qualms simply concatenating them.
To avoid cumulative rounding errors and ending up with a long string, save the toFixed
call for the very end of your program.
total = parseFloat(subtotal);
if(!$('#tablebody').is(':empty')){
$('#tablebody tr').each(function() {
total += parseFloat($(this).find('.subtotals').html());
});
}
totalString = total.toFixed(2);
Upvotes: 7
Reputation: 887215
.toFixed(2)
returns a formatted string with 2 decimal places.
Therefore, your +
is just concatenating strings.
You don't want that.
Upvotes: 1