Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "decimal.TryParse()" always return 0 for the input string "-1" in the below code?

Tags:

The below code should return the -1 decimal value but it's returning 0. Is there something I am doing wrong?

decimal validity = -1; validityStr = "-1";  decimal.TryParse(validityStr, NumberStyles.AllowDecimalPoint,                    CultureInfo.InvariantCulture, out validity); 

Expected Output:

-1

Actual Output:

0

like image 676
Bijay Yadav Avatar asked May 10 '19 09:05

Bijay Yadav


2 Answers

You forgot to tell TryParse that the leading sign is OK

decimal validity = -1; var validityStr = "-1";  decimal.TryParse(validityStr,      NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,     CultureInfo.InvariantCulture,      out validity);  
like image 130
Steve Todd Avatar answered Sep 23 '22 00:09

Steve Todd


As per documentation:

When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or Empty, is not a number in a valid format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uininitialized; any value originally supplied in result is overwritten.

Since the conversion failed, validity becomes 0. To make sure the conversion works you should add NumberStyles.AllowLeadingSign

like image 43
Djim Avatar answered Sep 24 '22 00:09

Djim