Mabden wrote:

"Fredrik Celin" <fr***********@bilia.se> wrote in message

news:fb**************************@posting.google.c om... I use IE 6.0 and does some calculations in a javascript.

If I run this code:

alert(1.4 - 0.5);

i get the result 0.8999999999 and not 0.9

Does anybody know why? Is this a bug in IE or what? Any fast and easy

ways to work around this problem?

Computers don't compute, sorry for any confusion. They can store a number in

memory, or retrieve a number from memory. They can also add one to a number,

or subtract one from a number. They can also add a number to another number.

That's about it.

--

Mabden

That's not really an explanation for what he's experiencing. For example take:

0.05+0.01

The above operation probably involved storing number(s) in memory, retrieving

number(s) from memory and adding a number to another number. All of these things

are things you say a computer can do, yet the result is not equal to 0.06. In

fact, the outcome of the operation 0.05+0.01 has nothing to do with a computers

ability to "compute", it has to do with a computers ability to represent decimal

values in binary.

If the question the OP posed were phrased like this

"If I run this code alert(one-third + two-thirds); I get 0.999999999... and not

1"

It becomes obvious why this occurred if you change the representation of

"one-third" to 0.33333.... and "two-thirds" to 0.666666... 0.3333... +

0.6666... = 0.9999..., not 1. No one would suggest for a moment that the human

doing this math isn't "computing" right, or is only capable of storing numbers

in their brain and adding them.

It's simply an issue of representation and loss of precision.

As for the solution, the solution is to round the result to the appropriate

level of precision required for the task. If the numbers you are computing

involve money, it's usually best to do all your math using integers only (ie -

store the values as number of cents, or tenths of cents, or whatever level of

precision is required) and do the final formatting on output of the result. In

other words, don't add 0.05 dollars to 0.01 dollars. Add 6 cents to 1 cent, then

position the decimal point two digits from the right when outputting the result

(note: don't divide by 100, because you risk introducing the same problem you

are trying to avoid, instead, actually output the result as a string, with the

decimal point positioned when you require it).

--

| Grant Wagner <gw*****@agricoreunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:

*

http://devedge.netscape.com/library/...ce/frames.html
* Internet Explorer DOM Reference available at:

*

http://msdn.microsoft.com/workshop/a...ence_entry.asp
* Netscape 6/7 DOM Reference available at:

*

http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla

*

http://www.mozilla.org/docs/web-deve...upgrade_2.html