Incorrect value of strToInt for negative numbers

Found a bug? Post information about it here so we can fix it!

Moderator: Moderators

Post Reply
User avatar
Rado1
Posts: 775
Joined: Wed May 05, 2010 12:16 pm

Incorrect value of strToInt for negative numbers

Post by Rado1 »

trace(intToStr(strToInt("-1"))) displays -29, trace(intToStr(strToInt("-10"))) displays -290, etc.
User avatar
Kjell
Posts: 1881
Joined: Sat Feb 23, 2008 11:15 pm

Post by Kjell »

Hi Rado,

You're right, support for negative numbers and filtering of non-numerical characters was never implemented in the function. Should only take a minute to add though. In the meantime, in case you ( or anyone else ) really need it right away .. use the following.

Code: Select all

int str2Int(string S)
{
  int R, F = 0;
  int L = length(S);

  for(int N=0; N<L; ++N)
  {
    int C = ord(subStr(S,N,1));

    if(C == 45)
    {
      if(N != 0)return 0; else F = 1;
    }
    else if(C > 47 && C < 58)
    {
      R = R*10+C-48;
    }
    else return 0;
  }

  if(F)R = 0-R;

  return R;
}
It returns 0 if the string is incorrect, so for instance "99.2" ( since that's not a integer ), "222-", "-49A" etc.

K
User avatar
Rado1
Posts: 775
Joined: Wed May 05, 2010 12:16 pm

Post by Rado1 »

I already use simpler, less robust, workaround, but this is not nice anyway.

Code: Select all

result = subStr(str, 0,1) == "-" ? strToInt(subStr(str, 1, length(str)-1))*-1: strToInt(str);
Post Reply