0

This kind of blows my mind..

http://pastebin.com/Q3MtpPpM

Turns out the output is "surprise!!". Doesn't this sort of undermine using JavaScript in some way if a program was going to use lots of floating point values?

magician11
  • 4,234
  • 6
  • 24
  • 39

2 Answers2

0

One way of comparing floats could be by converting them to String values using toFixed() method

var fl1 = 0.11;
var fl2 = 0.11;

if ( fl1.toFixed(10) == fl2.toFixed(10) )
{
  //same value
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Javascript numbers are 64 bit floating point. see this ECMAScript specification.

http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.19

Floating point arithmetic in any programming language is prone to errors and is not always guaranteed to be accurate. see following for more on Floating point airthmatic

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

for more see the following QA

Is floating point math broken?

And yes its a WAT, but following rules can help you avoid errors

  1. dont do equality checks
  2. in case of critical floats where you know maximum points after denomination for example currency store multiplied value by that base.

for currency store in cents instead of dollors.

54.67 as 5467 --- and divide by 100 before display.

For more read following post (its for c++ but will give insights on floating point erros)

http://www.codeproject.com/Articles/29637/Five-Tips-for-Floating-Point-Programming

Community
  • 1
  • 1
Mohit
  • 2,239
  • 19
  • 30