Solved

isnumeric function or equivalent

Posted on 2004-09-22
21
6,683 Views
Last Modified: 2008-01-09
What is the equivalent in Delphi for the isnumeric function or where can I find this function ?

Thank,

Sang-Do.

0
Comment
Question by:PHD
  • 6
  • 5
  • 4
  • +5
21 Comments
 
LVL 13

Expert Comment

by:BlackTigerX
Comment Utility
there's
IsNan
in the Math unit
Indicates when a variable or expression does not evaluate to a numeric value.
0
 
LVL 13

Expert Comment

by:BlackTigerX
Comment Utility
never mind... use StrToInt or StrToFloat, if they raise exception, then is not a number...

function IsNumeric(s:String): Boolean;
var num: Extended;
begin
  IsNumeric:=True;
  try
    num:= StrToFloat(s)
  except
      IsNumeric:=False;
  end;
end;
0
 
LVL 4

Expert Comment

by:Evarest
Comment Utility
function IsNumeric( Value: string ): boolean;
var
  Number: Extended;
  Error: Integer;
begin
  Val(Value, Number, Error);
  result := (Error = 0);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
 if IsInteger(Edit1.Text)
  then ShowMessage('This is a numeric value')
   else ShowMessage('This is not a numeric value');
end;

Error will also contain the position of the character that's not a numeric character.

Kind regards,
Evarest
0
 
LVL 2

Expert Comment

by:php4delphi
Comment Utility
unit IsNumericFunction;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,  StdCtrls;

type
  TForm1 = class(TForm)
    NumericCheck: TButton;
    procedure NumericCheckClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function IsNumeric(AValue : variant) : boolean;
var
 VarData : TVarData;
 E: Integer;
 R : real;
begin
  Result := false;
  VarData := TVarData(AValue);
  case VarData.VType of
    varSmallInt,
    varInteger,
    varBoolean,
    varShortInt,
    varByte,
    varWord,
    varLongWord,
    varInt64 :  Result := true;
    varSingle,
    varDouble,
    varCurrency : Result := true;
    varString : begin
                  if VarIsEmpty(AValue) then
                   Result := false
                     else
                       begin
                         Val(AValue, R, E);
                         Result := (E = 0);
                       end;
                end;
    end;
end;

procedure TForm1.NumericCheckClick(Sender: TObject);
var
  MyCheck : boolean;
begin
 MyCheck := IsNumeric(53);   // Returns True.
 MyCheck := IsNumeric('459.95');   // Returns True.
 MyCheck := IsNumeric('45 Help');   // Returns False.
end;

end.
0
 
LVL 12

Expert Comment

by:Ivanov_G
Comment Utility
function IsNumeric(str : String) : Boolean;
var
  tmp_int    : Integer;
  tmp_real   : Real;
  fl         : byte;
begin
  Result := True;
  fl := 2;
  // try to convert to integer
  try
    tmp_int := StrToInt(str);
  except
    Dec(fl);
  end;
  // try to convert to float
  try
    tmp_real := StrToFloat(str);
  except
    Dec(fl);
  end;
  if fl > 0 then
    Result := True
  else
    Result := False;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if IsNumeric(Edit1.Text) then
    ShowMessage('Yes')
  else
    ShowMessage('No');
end;
0
 
LVL 27

Expert Comment

by:kretzschmar
Comment Utility
hmm, too late
the val-procedure i would use as evarest suggested,
but replacing a regional decimalpoint (, in my country) with a dot i would do before

meikl ;-)
0
 
LVL 13

Expert Comment

by:BlackTigerX
Comment Utility
so basically is better to use StrToFloat or StrToInt =o)
0
 
LVL 2

Expert Comment

by:php4delphi
Comment Utility
IsNumeric function returns True if the entire expression is recognized as a number; otherwise, it returns False.
It means it should accept not only string, but also integer, float, etc...

In case of StrToFloat or StrToInt is possible to check only string, so this is not equivalent to IsNumeric
0
 
LVL 4

Expert Comment

by:Evarest
Comment Utility
I was in the impression that a numeric value was a float or integer. An integer value is an integer :-)

Can be that i'm mistaken, but my function will indeed find floats to be numeric. Also, php4delphi's function in the way he posted it, will return true for floats as well. Of course both functions can easily be altered to not to return true on float values...

Kind regards,
Evarest
0
 
LVL 2

Assisted Solution

by:php4delphi
php4delphi earned 150 total points
Comment Utility
Indeed, float or integer is numeric, the problem resides not here.
I repeated again: the question is about equivalent in Delphi for the isnumeric function.
IsNumeric is VB fuction that can accept ANY parameter, not only string.
Your function accepts only STRING as parameter and it's not an equivalent for IsNumeric, as it declared in VB, you made IsStringIsNumeric function. I hope now I made myself clear
 
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 13

Expert Comment

by:BlackTigerX
Comment Utility
it depends on what exactly he needs, your function is the most generic one, but also the slowest
0
 
LVL 2

Expert Comment

by:php4delphi
Comment Utility
IMHO he needs what he asked. Otherwise the solution of Evarest can be accepted without any doubt.
0
 
LVL 13

Expert Comment

by:BlackTigerX
Comment Utility
well, that may or may not be the case... I would prefer to hear from him what he needs this function for
0
 
LVL 4

Expert Comment

by:Evarest
Comment Utility
Indeed, let's wait for PHD's decision...
0
 
LVL 12

Expert Comment

by:esoftbg
Comment Utility
unit IsNum;

interface

function IsNumeric(E: Extended): Boolean; overload;
function IsNumeric(D: Double): Boolean; overload;
function IsNumeric(R: Real): Boolean; overload;
function IsNumeric(R48: Real48): Boolean; overload;
function IsNumeric(C: Comp): Boolean; overload;
function IsNumeric(CU: Currency): Boolean; overload;
function IsNumeric(SI: Single): Boolean; overload;
function IsNumeric(I: Integer): Boolean; overload;   // equal to Longint
function IsNumeric(CA: Cardinal): Boolean; overload; // equal to Longword
function IsNumeric(B: Byte): Boolean; overload;
function IsNumeric(SH: Shortint): Boolean; overload;
function IsNumeric(SM: Smallint): Boolean; overload;
function IsNumeric(W: Word): Boolean; overload;
function IsNumeric(I64: Int64): Boolean; overload;
function IsNumeric(S: string): Boolean; overload;

implementation

function IsNumeric(E: Extended): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(D: Double): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(R: Real): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(R48: Real48): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(C: Comp): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(CU: Currency): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(SI: Single): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(I: Integer): Boolean; overload;   // equal to Longint
begin
  Result := True;
end;

function IsNumeric(CA: Cardinal): Boolean; overload; // equal to Longword and DWORD
begin
  Result := True;
end;

function IsNumeric(B: Byte): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(SH: Shortint): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(SM: Smallint): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(W: Word): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(I64: Int64): Boolean; overload;
begin
  Result := True;
end;

function IsNumeric(S: string): Boolean; overload;
begin
  Result := False;
end;

end.
0
 
LVL 4

Expert Comment

by:Evarest
Comment Utility
Don't know why to use all these overloaded procs if it can be done in much less lines... However, esoftbg also seems to think that a Numeric value isn't just an integer value :-)

Kind regards,
Evarest
0
 
LVL 4

Expert Comment

by:Evarest
Comment Utility
Sorry, I get it now: your function will also accept non string values...
0
 
LVL 4

Accepted Solution

by:
Evarest earned 350 total points
Comment Utility
The updated version of my code:

function IsNumeric( Value: Variant ): boolean; // <-- string has been changed in Variant. About 3 times slower but more generic.
var
  Number: Extended;
  Error: Integer;
begin
  Val(Value, Number, Error);
  result := (Error = 0);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
 if IsNumeric(Edit1.Text)
  then ShowMessage('This is a numeric value')
   else ShowMessage('This is not a numeric value');
end;

Evarest
0
 
LVL 17

Expert Comment

by:Wim ten Brink
Comment Utility
If the value you're checking is a Variant or OleVariant then just use the function VarType. The function VarType(MyVariant) will return one of these values:
varEmpty - The Variant is Unassigned.
varNull - The Variant is Null.
varSmallint - 16-bit signed integer (type Smallint).
varInteger - 32-bit signed integer (type Integer).
varSingle - Single-precision floating-point value (type Single).
varDouble - Double-precision floating-point value (type Double).
varCurrency - Currency floating-point value (type Currency).
varDate - Date and time value (type TDateTime).
varOleStr - Reference to a dynamically allocated UNICODE string.
varDispatch - Reference to an Automation object (an IDispatch interface pointer).
varError - Operating system error code.
varBoolean - 16-bit boolean (type WordBool).
varVariant - A Variant.
varUnknown - Reference to an unknown OLE object (an IUnknown interface pointer).
varByte - A Byte
varStrArg - COM-compatible string.
varString - Reference to a dynamically allocated string. (not COM compatible)
varAny - A CORBA Any value.

With newer Delphi versions there could be newer values. Just check if the type is the one you would like.

procedure Val(S; var V; var Code: Integer);

If the value is a string, you could check if it's a value by using the Val(MyString, MyValue, Error) where MyValue will have the numeric value if it's a number, else Error will be bigger than 0, indicating the position of the invalid character in the string. Be aware, if you use an Integer as MyValue, it will check if MyString is an integer. If you use a Float, MyString can be any real number. The Val function can also convert hexadecimal values if you put a $ character in front of the value. Thus: Val('$0A', MyValue, Error); will result in the value 10 to be assigned to MyValue. The Val function also supports the exponential syntax of numbers, thus Val('1.2E3', MyValue, Error) ; is valid too, resulting in 1200 being assigned to MyValue. But Val('1.23', MyValue, Error); will fail if MyValue is of type integer, with Error set to 2. (Position of the dot, the illegal character.)
0
 
LVL 1

Expert Comment

by:Balshe
Comment Utility


Function IsNumeric(Str:String) :boolean;
  Const Numeric='1234567890.';
Var
  I:Integer;
  J:Integer;
  t1:string;
Begin
  str:=trim(Str);
  if length(str)=0 then
    Begin
      Result:=false;
      exit;
    end;

  j:=pos('.',str);
  if (j=1) and (Length(Str)=1) then
    Begin
      Result:=false;
      exit;
    end;
  if j>0 then
    Begin
      t1:=copy(str,j+1,Length(Str));
      j:=pos('.',t1);
      if j>0 then
        Begin
          result:=false;
          exit;
        End;
    end;


  result:=true;
  For I:=1 to length(str) do
      if pos(str[i],Numeric)=0 then
        Begin
          Result:=false;
          Break;
        end;
end;

//------------------------------------------------------------------------------
0
 
LVL 1

Expert Comment

by:Balshe
Comment Utility
So what happened to this Question ????????
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now