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
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With