Click here to Skip to main content
15,887,328 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Validate numeric textbox using int.tryparse visual C#.NET

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
5 Oct 2011CPOL 6.6K  
Here is some old Delphi code that you could use to get more out of floating points strings before using TryParse().It will sanitize numbers like .25E4 or 10.E2 or -.24, all illegal in Double.TryParse.The code will also replace all non-floating point characters by a decimal separator (the...

Here is some old Delphi code that you could use to get more out of floating points strings before using TryParse().


It will sanitize numbers like .25E4 or 10.E2 or -.24, all illegal in Double.TryParse.


The code will also replace all non-floating point characters by a decimal separator (the 'easiest' way I found to get rid of locale problems).


Delphi
function ExpandFloatStr(Value: string): string;
var
  i                             : Integer;
  sep                           : Char;
begin
  //Use Actual Separator here because Delphi has yet to change
  //if we arrive here from the SystemChange Notification
{$WARNINGS OFF}
  sep := GetLocaleChar(GetThreadLocale, LOCALE_SDECIMAL, '.');
{$WARNINGS ON}

  Result := Value;
  {----Correct DecimalSeparator, Will this Recurse?}

  for i := 1 to Length(Result) do
    if not ((Result[i] in ['0'..'9', '-', '+', 'e', 'E']) or IsAlpha(Result[i])) then
      Result := StringReplace(Result, Result[i], sep, [rfReplaceAll]);

  {----Correct .xx to 0.xx}
  if (Copy(Result, 1, 1) = sep) then
    Result := '0' + Result;

  {----Correct +/-.xx to +/-0.xx}
  if (Copy(Result, 1, 2) = '-' + sep) or (Copy(Result, 1, 2) = '+' + sep) then
    Result := copy(Result, 1, 1) + '0' + copy(Result, 2, Length(Result));

  {----Correct +/-xxx.E to +/-xxx.0E}
  if (Pos('E', Result) > 1) and (Copy(Result, Pos('E', Result) - 1, 1) = sep) then
    Result := Copy(Result, 1, Pos('E', Result) - 1) + '0' + 
              Copy(Result, Pos('E', Result), Length(Result));

  {----Correct +/-xx. to +/-xx.0 but NOT +/-xxE+/-yy.}
  {
    if (Copy(text,Length(text),1)=sep)
      then text:=text+'0';
  }
end;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Open Universiteit
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --