#13 Integer evaluates using Float precision

open
5
2005-08-03
2005-08-03
Robert Sucher
No

Integer evaluates using Float precision

1. A declared integer can become a float-type for all
practical purposes after a non-integer division between
two integers, i.e., division of 2 integers using the '/'
division operator instead of the div operator.
2. Per the DWSII Reference, "IntToStr converts an
integer into a string containing the decimal
representation of that number." It's interesting that a true
integer division above would produce a result of '1', but
IntToStr returns '2' as a result of rounding, not
truncating.

var i1: integer = 5;
var i2: integer = 3;
var i3, i4: integer;

i3 := i1 / i2;
i4 := 2 * i3;

if i3 = 1 then
ShowMessage( ' 5/3 = 1 : TRUE; correct int arithmetic,
which is produced by 5 div 3' )
else if i3 = 2 then
ShowMessage( ' 5/3 = 2 : TRUE' )
else if i3 < 2 then
begin
ShowMessage( 'Neither expression is TRUE, but
IntToStr says i3 is 2...' );
ShowMessage( 'IntToStr( i3 ) = ' + IntToStr( i3 ) ); //
Shows: 2 (rounded up)
ShowMessage( 'FloatToStr( i3 ) = ' + FloatToStr( i3 ) ); //
Shows actual value: 1.66666666666667
end;

Discussion