Mega Code Archive

 
Categories / Delphi / Examples
 

Working with floating point, double, single, real, extended types

Question: I have two floating point values that are the same, yet when I compare them using " if d1 = d2 then .. " or " if d1 <> d2 then .. " the results are incorrect. Is this a bug? Answer: No. Unlike integers, IEEE floating point numbers are only approximates, not exact numbers. You should never use = or <> to compare two floating point numbers. Instead, subtract the two numbers and compare them against a very small number. Example: if abs(d1-d2) < 0.00001 then ShowMessage('D1 and D2 are equal');