1

I have this function:

function doCalc() {
  var total = 0;
  $('tr').each(function() {
      $(this).find('span.amount').html($('input:eq(0)', this).val() * $('input:eq(1)', this).val());
  });    
} 

$(this).keyup(doCalc);    

and for example if I multiply 12 * 1.90 it always shows 22.799999999999997 How to format it to 22.80 ? Thanks in advance

bipen
  • 36,319
  • 9
  • 49
  • 62
  • duplicate: http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals – ruuter Apr 24 '13 at 07:07

3 Answers3

4
var num = 5.56789;
var n=num.toFixed(2); 

The result of n will be: 5.57

Anshuman Jasrotia
  • 3,135
  • 8
  • 48
  • 81
  • I tried this and it is working but where to apply toFixed(2); in my code? sorry for being ... :) – user1820186 Apr 24 '13 at 07:06
  • Try this $(this).find('span.amount').html(($('input:eq(0)', this).val() * $('input:eq(1)', this).val()).toFixed(2)); – Anshuman Jasrotia Apr 24 '13 at 07:08
  • You should add toFixed(2) also to first input. Otherwise if first number will be for example 7.9, you again have same problem. So answer to @user1820186 is to add toFixed(2) to all input values. ps. I see no one accepted. – ruuter Apr 24 '13 at 07:12
  • I have added toFixed() to the product of two inputs so there is no need to add it separately to individual inputs. – Anshuman Jasrotia Apr 24 '13 at 07:14
3

you can use toFixed

var test = 10.231;
alert(test.tofixed(test))

returns 10.23
Joel Harkes
  • 10,975
  • 3
  • 46
  • 65
2

You can multiply the result by 100 and then divide by 100.

or you can also use result.toFixed(2);