Search code examples
delphidelphi-xe2firemonkey

Delphi TNumberbox returns single; how to get to a standard integer?


TNumberbox and TSpinEdit return values defined as type single. I want to use these values to do simple integer arithmetic, but I can't cast them successfully to the more generalized integer type, and Delphi gives me compile-time errors if I try to just use them as integers. This code, for example, fails with

"E2010 Incompatible types: 'Int64' and 'Extended'":

var
    sMinutes: single;
    T: TDatetime;
begin
sMinutes :=Numberbox1.value;
T :=incminute(Now,sMinutes);

All I want to do here is have the user give me a number of minutes and then increment a datetime value accordingly. Nothing I've tried enables me to use that single in this way.

What am I missing??


Solution

  • Just truncate the value before using it:

    var
      Minutes: Integer;
      T: TDateTime;
    begin
      Minutes := Trunc(NumberBox1.Value);
      T := IncMinute(Now, Minutes);
    end;
    

    Depending on your particular needs, you may need to use Round instead. It will correctly round to the nearest integer value, making sure that 1.999999999999 correctly becomes integer 2; Trunc would result in 1 instead. (Thanks to Heartware for this reminder.)

    var
      Minutes: Integer;
      T: TDateTime;
    begin
      Minutes := Round(NumberBox1.Value);
      T := IncMinute(Now, Minutes);
    end;
    

    Trunc and Round are in in the System unit.