0

I am trying to use eval() for calculator i am making, but if when i try this

console.log(eval("5.2-5"));

It returns

0.20000000000000018

Why is this happening.Thank you for your time.

August
  • 1,722
  • 5
  • 20
  • 37

2 Answers2

1

Javascript evaluates "5.2-2" to a floating point number, which precision is not guaranteed.
If you need a fixed precision you could use

console.log(eval("5.2-5.0").toFixed(2)):
Luca Putzu
  • 1,438
  • 18
  • 24
0

This is due to how Javascript handles floating point precision. Please see How to deal with floating point number precision in JavaScript? for more information

Short answer: Due to the nature of how computers process floats, this means floating point accuracy actually breaks down past a certain point. This is what you're seeing.

Community
  • 1
  • 1
millerbr
  • 2,951
  • 1
  • 14
  • 25
  • [Javascript *does* use floats](http://www.ecma-international.org/ecma-262/5.1/#sec-8.5) (doubles, actually). It may use integers, but will bail to doubles if math could result in a decimal result. – ssube Mar 11 '16 at 15:46
  • Really? I was always under the impression that there was no such thing as an actual float/double, and that the engine always used an integer then converted to something we think of as a float/double? But I could easily be wrong! – millerbr Mar 11 '16 at 15:47