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
  • 45,272
  • 113
  • 282
  • 475
  • 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,601
  • 3
  • 30
  • 57
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
  • 34,863
  • 6
  • 72
  • 90
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,430
  • 1
  • 39
  • 50