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
try
{
realValue = System.Convert::ToDecimal(strValue);
print realValue;
}
catch
{
print "caught";
}   pause;   }


Reference:


http://msdn.microsoft.com/en-us/library/hf9z3s65.aspx

1 comment:

mourad ben mahmoud said...

HELLO,

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.