65.9K
CodeProject is changing. Read more.
Home

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

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 5, 2011

CPOL
viewsIcon

6700

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).

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;