Determine if a string is numeric: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 1: | Line 1: | ||
{{task}} |
{{task}} |
||
Demonstrates how to implement a custom IsNumeric method in other .NET/Mono languages that do not wish to reference the Microsoft.VisualBasic.dll assembly. |
Demonstrates how to implement a custom IsNumeric method in other .NET/Mono languages that do not wish to reference the Microsoft.VisualBasic.dll assembly. |
||
==[[Ada]]== |
|||
[[Category:Ada]] |
|||
The first file is the package interface containing the declaration of the Is_Numeric function. |
|||
package Numeric_Tests is |
|||
function Is_Numeric(Item : in String) return Boolean; |
|||
end Numeric_Tests; |
|||
The second file is the package body containing the implementation of the Is_Numeric function. |
|||
package body Numeric_Tests is |
|||
---------------- |
|||
-- Is_Numeric -- |
|||
---------------- |
|||
function Is_Numeric (Item : in String) return Boolean is |
|||
Result : Boolean := True; |
|||
begin |
|||
declare |
|||
Int : Integer; |
|||
begin |
|||
Int := Integer'Value(Item); |
|||
exception |
|||
when others => |
|||
Result := False; |
|||
end; |
|||
if Result = False then |
|||
declare |
|||
Real : Float; |
|||
begin |
|||
Real := Float'Value(Item); |
|||
Result := True; |
|||
exception |
|||
when others => |
|||
null; |
|||
end; |
|||
end if; |
|||
return Result; |
|||
end Is_Numeric; |
|||
end Numeric_Tests; |
|||
The last file shows how the Is_Numeric function can be called. |
|||
with Ada.Text_Io; use Ada.Text_Io; |
|||
with Numeric_Tests; use Numeric_Tests; |
|||
procedure Isnumeric_Test is |
|||
S1 : String := "152"; |
|||
S2 : String := "-3.1415926"; |
|||
S3 : String := "Foo123"; |
|||
begin |
|||
Put_Line(S1 & " results in " & Boolean'Image(Is_Numeric(S1))); |
|||
Put_Line(S2 & " results in " & Boolean'Image(Is_Numeric(S2))); |
|||
Put_Line(S3 & " results in " & Boolean'Image(Is_Numeric(S3))); |
|||
end Isnumeric_Test; |
|||
The output of the program above is: |
|||
152 results in TRUE |
|||
-3.1415926 results in TRUE |
|||
Foo123 results in FALSE |
|||
==[[C sharp|C#]]== |
==[[C sharp|C#]]== |