Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

0.00/5 (No votes)
5 Oct 2011CPOL 6.7K  
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)