2

Possible Duplicate:
Is JavaScript’s Math broken?

Funny question, but why at 16.1 javascript become "crazy"? :)

Code :

var value1=16.1;
var value2=16.2;

console.log(value1 * 1000);
console.log(value2 * 1000);

Output :

16100.000000000002
16200 

Why?

Community
  • 1
  • 1
markzzz
  • 47,390
  • 120
  • 299
  • 507

2 Answers2

1

It's not a javascript problem, it's a problem related to any programming language using floating point numbers, see

Is floating point math broken?

for explanation of the root problem and for some useful workarounds too.

Community
  • 1
  • 1
Nelson
  • 49,283
  • 8
  • 68
  • 81
1

That's because javascript casts everything to a double internally. As a result, all calculations pick up some noise due to floating point inaccuracy: Floating point inaccuracy examples

One way to fix this issue, is to just round down to the nearest int after all intermediate calculations.

Answer Copy From Here

Community
  • 1
  • 1
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110