by **mgreen** on Tue Feb 07, 2006 1:33 pm

This behavior is actually normal. Floating point numbers have only a limited precision. Typically, "single" precision numbers have somewhere between 7-8 decimal digits of precision and "double" precision numbers approximately double that. Usually they are binary floating point with the exponent in bits rather than decimal digits. As a result, numbers that appear to be represented exactly like "1.80" are actually represented in binary with very small errors in the least significant binary digits. When you repeatedly add them, the error accumulates as you have seen. The solution is to use double precision sometimes, to round the result to a smaller number of decimal places when displaying it, or to do the calculation as integer fixed point and to simply display the result with a decimal point inserted. This is often done for currency amounts. You would use "#define SOFT_PREIS 180", declare all currency values as integer, and write a display function that takes an integer value, converts it to a string like "180" and inserts a decimal point to make "1.80". You have to account for numbers smaller than 100 like ".99" or ".09". Some languages (and computers) did all their floating point calculations in decimal representing each digit in 4 bits with the exponent as a decimal exponent, but this is slower than doing it all in binary and the amount of precision in a specific amount of storage is less (64 bits would provide maybe 13 digits rather than 16).

-----

Michael Green