Solved

isnumeric function or equivalent

Posted on 2004-09-22
21
6,905 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 4
  • +5
21 Comments
 
LVL 13

Expert Comment

by:BlackTigerX
ID: 12124556
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
ID: 12124582
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
ID: 12124618
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Expert Comment

by:php4delphi
ID: 12124927
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
ID: 12125376
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
ID: 12125617
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
ID: 12125718
so basically is better to use StrToFloat or StrToInt =o)
0
 
LVL 2

Expert Comment

by:php4delphi
ID: 12125769
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
ID: 12126049
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
ID: 12126146
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
 
LVL 13

Expert Comment

by:BlackTigerX
ID: 12126242
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
ID: 12126306
IMHO he needs what he asked. Otherwise the solution of Evarest can be accepted without any doubt.
0
 
LVL 13

Expert Comment

by:BlackTigerX
ID: 12126654
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
ID: 12126889
Indeed, let's wait for PHD's decision...
0
 
LVL 12

Expert Comment

by:esoftbg
ID: 12130128
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
ID: 12131444
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
ID: 12131468
Sorry, I get it now: your function will also accept non string values...
0
 
LVL 4

Accepted Solution

by:
Evarest earned 350 total points
ID: 12131484
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
ID: 12132741
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
ID: 12154232


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
ID: 12187520
So what happened to this Question ????????
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

695 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