Wednesday, 13 February 2013

str2Num doesn’t work as expected

If you are trying to convert a string to a decimal, you might notice that it doesn’t always work. It is very sensitive on the formatting of the string.

Input Output (str2Num) Output (str2NumOk) System.Convert::ToDecimal(strValue);
1 23 1 false catch the exception as nothing is resolved
1abc 1 false catch the exception as nothing is resolved
1,123.00 1 false 123.00
You can use the method str2NumOk() to check

Alternatively, you could use the .NET system method to convert the string to a decimal. This handles conversions a little better.

real   decimalValue = System.Convert::ToDecimal(strValue);

Sample job code to test it out the third example.

static void testStringToNumeric(Ar  gs _args)
str strValue;
real realValue;   strValue = "1,123.00";
print str2num(strValue); //returns 1
print str2NumOk(strValue); //returns false
realValue = System.Convert::ToDecimal(strValue);
print realValue;
print "caught";
}   pause;   }



mourad ben mahmoud said...


Thank you for your post, but when i use num2str it rounds to 2 decimals, even if i use the System.Convert::ToDecimal. the result is always rounded. is there a way to have a result with more decimals ?

thank you.

Blogger said...

If you want your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (even if they're dating somebody else now) you must watch this video
right away...

(VIDEO) Win your ex back with TEXT messages?