delphidelphi-7precisionfloating-accuracytdatetime

Frac function losing precision


I have a TDateTime variable which is assigned a value at runtime of 40510.416667. When I extract the time to a TTime type variable using the Frac function, it sets it to 0.41666666666. Why has it changed the precision of the value and is there a workround to retain the precision from the original value ie. to set it to 0.416667.


Solution

  • One of the reason for the loss of precision is that TDateTime is a double, and Frac's parameter and return value is of type Extended.

    When converting floating points from one type to another, some precision can be lost. (Same goes when doing arithmetic on them).

    To compare float value correctly, you should use the CompareValue function from the unit Math.