0

Tried :

var a=10.3;
var b=2.3;
alert(a+b);

but I get 12.600000000000001. I know JavaScript is loosely typed, but I hope I can do a sum :)

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • so your question is about formatting a number with a limited number of decimals? – Dan D. Feb 14 '12 at 08:51
  • This inaccuracy is rather due to how [floating point numbers are represented in binary](http://www.google.com/search?What%20every%20computer%20scientist%20should%20know%20about%20floating-point%20arithmetic). – Gumbo Feb 14 '12 at 08:55

3 Answers3

2

you can use toFixed() method also

var a=10.3;
var b=2.3;
alert((a+b).toFixed(1));​

Works in chrome

Raghuveer
  • 2,630
  • 3
  • 29
  • 59
1

Multiply to the precision you want then round and divide by whatever you multiplied by:

var a=10.3;
var b=2.3;
alert(Math.round((a+b) * 10) / 10);

http://jsfiddle.net/DYKJB/3/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
1

It's not about the typing but about the precision of floating point types. You need to round for presentation.

Floating point types are not a good choice if you need exact values. If you want to express currency values express them as cents or use an appropriate library for this.

Hauke Ingmar Schmidt
  • 11,559
  • 1
  • 42
  • 50