The Problem
The problem is that this overload of TryParse
takes that number as
an NumberStyles.Integer
- meaning it is looking for a format that
does not contain any .
. seeing in Reference Source it is
actually doing this:
public static bool TryParse(String s, out Int16 result) {
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
To show that the .
is the problem change as following and it will
work:
decimal myDecimal = 19M;
var succeeded = short.TryParse(myDecimal.ToString(), out newVal);
How Does Double work but decimal fails
The reason why with double it works is because of how it is returned in the ToString
:
decimal val1 = 19.00M;
double val2 = 19.00;
val1.ToString() // "19.00"
val2.ToString() // "19"
The Fix
To be able to parse your original input use instead the overload where you provide the NumberStyle
and Format
:
var succeeded = short.TryParse(myDecimal.ToString(), NumberStyles.Number, NumberFormatInfo.CurrentInfo, out newVal);
The NumberStyle.Number
allows:
AllowLeadingWhite
, AllowTrailingWhite
, AllowLeadingSign
,
AllowTrailingSign
, AllowDecimalPoint
, AllowThousands