Incorrect value of strToInt for negative numbers
Moderator: Moderators
Incorrect value of strToInt for negative numbers
trace(intToStr(strToInt("-1"))) displays -29, trace(intToStr(strToInt("-10"))) displays -290, etc.
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.
It returns 0 if the string is incorrect, so for instance "99.2" ( since that's not a integer ), "222-", "-49A" etc.
K
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;
}
K
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);