jojo1711
jojo1711

Reputation: 113

Round of number to 2 decimal places

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

Answers (3)

Ihor Malaniuk
Ihor Malaniuk

Reputation: 161

The main problem with toFixed func that it returns a string instead of a number.

There are a few possible solutions:

  1. improved solution from you

    Number(val.toFixed(2))
    

    OR

    parseFloat(val.toFixed(2))
    
  2. The solution in more Math way.

    Math.round(val*100)/100
    

Upvotes: 6

demkovych
demkovych

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

Vasanth Gopal
Vasanth Gopal

Reputation: 1285

Try the following

const num = Number($(this).find(".amount").val().replace(/,/g, ''));
const amt = Math.round(num * 100) / 100;

Upvotes: 2

Related Questions