Raffaele Rossi
Raffaele Rossi

Reputation: 3127

Delphi check if double is an integer or not

I need to test if a double is an integer or not. Basically this is an example of the rule:

In order to do this I'd make an if (result mod 1) = 0 then and see the if it returns true or false. Consider that result is a double. By the way the compiler gives me this error:

[dcc32 Error] Unit1.pas(121): E2015 Operator not applicable to this operand type

How can I solve this problem? Note that my numbers are in this format ##.##### so I haven't many problems with the floating point precision.

In general I'd use if (result % 1 == 0) {} but in Delphi this does not work.

Upvotes: 3

Views: 5611

Answers (4)

TomB
TomB

Reputation: 760

A Variation on @Alberto's answer. Just refined slightly to allow one to choose how precise (or imprecise) you want to be:

// is the passed FP number effectively an "integer";
// i.e. when rounded to AToPlaces decimal places, does it have only zero after dec point?
// AToPlaces -ve => after the dec point; same convention as for RoundTo; range -20 .. +20
  
function IsInteger(AFloat: Extended; AToPlaces: TRoundToEXRangeExtended = -3): boolean;
begin
  // Careful, this didn't work until I switched the order of Frac and RoundTo
  result := RoundTo(frac(AFloat), AToPlaces) = 0;
end;

Upvotes: 0

Todd Hayden King
Todd Hayden King

Reputation: 11

That comparison would work in Freepascal....

{$mode objfpc}{$R+}
uses math;
var
  a:double =  5.2;
  b:double =  5.0;
begin
  writeln(a mod 1 = 0);
writeln(b mod 1 = 0);
end.

But it won't work in Delphi, I know...

In Delphi it should be with fmod:

uses math;
var
  a:double =  5.2;
  b:double =  5.0;
begin
  writeln(fmod(a,1) = 0);
  writeln(fmod(b,1) = 0);
end.

Upvotes: 1

zeus
zeus

Reputation: 13345

maybe you want also to take care about the float imprecision, in this way you can do something like this :

if comparevalue(aValue, round(aValue), Tepsilon.vector) = 0 then 
  hasnodecimal 
else 
  hasdecimal

Upvotes: -1

Alberto Miola
Alberto Miola

Reputation: 4751

You can use the function frac declared in the System unit of Delphi. Try with this code:

if ( frac(result) = 0 ) then
 ShowMessage('is zero')
else
 ShowMessage('is NOT zero');
end;

Check the documentation for details about the function. What you are doing is wrong because in Delphi the keyword mod only works with Integers.


Note. I have tested this with numbers such as 45.1234 and the code is correct. I see that you have a little number of digits in your double so there shouldn't be problems. I am not sure how accurate that function is, but in this case you don't have to worry.

Upvotes: 9

Related Questions