Reputation: 113
How can I round of the number to 2 decimal places in below method ?
$('.total').each(function() {
var amt = Number($(this).find(".amount").val().replace(/,/g, ''));
subtotal += amt;
});
I tried to do Number($(this).find(".amount").val().toFixed(2).replace(/,/g, ''));
but it's not working,
Really appreciate your help on this.
Upvotes: 3
Views: 12034
Reputation: 161
The main problem with toFixed
func that it returns a string instead of a number.
There are a few possible solutions:
improved solution from you
Number(val.toFixed(2))
OR
parseFloat(val.toFixed(2))
The solution in more Math way.
Math.round(val*100)/100
Upvotes: 6
Reputation: 8817
If value is a string:
parseFloat(amt).toFixed(2);
If value is a number:
amt.toFixed(2);
Or you can use solution from [MDN][https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round]:
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
Upvotes: 1
Reputation: 1285
Try the following
const num = Number($(this).find(".amount").val().replace(/,/g, ''));
const amt = Math.round(num * 100) / 100;
Upvotes: 2