views:

105

answers:

3

Hello,

I'm trying to build a calculator in Flex / actionscript 3 but have some weird results using the class Math :

trace(1.4 - .4); //should be 1 but it is 0.9999999999999999
trace(1.5 - .5); //should be 1 and it is 1
trace(1.444 - .444); //should be 1 and it is 1
trace(1.555 - .555); //should be 1 but it is 0.9999999999999999

I know there are some issues with floating point numbers, but as you can see, it should at least fail for all of my examples, am I right?

How the problem is solved in other calculators and how should I proceed in order to build a usable calculator in Actionscript 3 please?

Thank you in advance, Adnan

+3  A: 

Welcome to IEEE 754 floating point. Enjoy the inaccuracies. Use a fixed-point mechanism if you want to avoid them.

Ignacio Vazquez-Abrams
deleted my answer, no point having 3 answers with the same link in them ;-)
Andy E
How to know how many fixed points do I need ?How for example the Windows calculator solve this issue ?
Adnan Doric
Normally the fixed point library will handle details like this by expanding the number of decimal places as needed. If you're doing it "manually" by using ints instead then just increase the exponent of the number with the smaller number of places and then proceed as normal.
Ignacio Vazquez-Abrams
+1  A: 

Your results are to be expected, and will be observed in any programming language with a floating point datatype. Computers cannot accurately store all numbers, which causes edge cases like the ones you posted.

Read up on floating point accuracy problems at Wikipedia.

Aistina
A: 

I would assume that most calculators display fewer decimal places than the precision of their floating point. Rounding to fewer decimal places than your level of precision should alleviate this sort of problem, but it won't solve all of the issues.

tvanfosson