Short.Parse with decimal error

I have a decimal value

decimal myDecimal = 19.0000M;

I am trying to convert this to a short value.

short newVal;
short.TryParse(myDecimal.ToString(), out newVal); // False

but it fails. If I use double, that's fine.

Why is this failing?

thank

+4
source share
6 answers

Problem

  • The problem is that this overload TryParsetakes this number as a NumberStyles.Integer- meaning it is looking for a format that does not contain .. seeing the Help source , this actually does it:

    public static bool TryParse(String s, out Int16 result) {
       return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
    }
    
  • To show that .this is a problem change, as indicated below, and this will work:

    decimal myDecimal = 19M;
    var succeeded = short.TryParse(myDecimal.ToString(), out newVal);
    

Like Double work but decimal error

, double , - , ToString:

decimal val1 = 19.00M;
double val2 = 19.00;

val1.ToString() // "19.00"
val2.ToString() // "19"

, , NumberStyle Format:

var succeeded = short.TryParse(myDecimal.ToString(), NumberStyles.Number, NumberFormatInfo.CurrentInfo,  out newVal);

NumberStyle.Number :

  • AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, AllowThousands
+2

, :

short.TryParse(myDecimal.ToString(), NumberStyles.Integer | NumberStyles.AllowDecimalPoint, 
           System.Globalization.CultureInfo.InvariantCulture, out newVal);
+4

AllowDecimalPoint , : DonNetFiddle

decimal myDecimal = 19.0000M;
short newVal;

short.TryParse(myDecimal.ToString(), NumberStyles.AllowDecimalPoint , CultureInfo.InvariantCulture, out newVal);
+1

, decimal . , :

decimal myDecimal = 19.0000M;
decimal myDecimal2 = 19.000000M;
Console.WriteLine(myDecimal.ToString());
Console.WriteLine(myDecimal2.ToString());

//OUTPUT
19,0000
19,000000
0

, myDecimal.ToString() : 19.000 short.Tryparse() .

The solution is not to convert to string, but directly between decimal and short (as luki shows):

short shortVal = Convert.ToInt16 (myDecimal);

0
source

Try: Convert.ToInt16 (myDecimal);

-1
source

Source: https://habr.com/ru/post/1658922/


All Articles