34

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

Now that I have got a bit of script to add values in to a div with a total in it, I then try to divide the values by 100 to give me a decimal number (to make it look like currency).

After this the script works and gives me a nice decimal float, sometimes though a large recurring number comes after, I want to limit this to two decimals using the script i already have so was wondering if someone could implement something into my current script.

$(document).ready(function() {
  $('.add').click(function() {
     $('#total').text(parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100);
  });
})
Community
  • 1
  • 1
Mr Dansk
  • 766
  • 3
  • 8
  • 23

3 Answers3

87

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
29

Try to use this

parseFloat().toFixed(2)
joni_demon
  • 656
  • 6
  • 12
10

you can use just javascript for it

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52