Convert decimal to ushort

1

I need to convert a decimal value to ushort in my application:

Is there a possibility?

If yes, how to convert?

I tried to use Convert.ToInt16(value) , but it did not work.

Example in console:

static void Main(string[] args)
{
   decimal value= 15;
   //Nao é possivel converter, pergunta se existe uma conversao explicita...
   ushort newValue = Convert.ToInt16(value);

   Console.WriteLine(newValue);
   Console.ReadKey();
}
    
asked by anonymous 01.02.2018 / 15:13

3 answers

3

Essentially you should not do this for two reasons:

  • You are probably losing data since a decimal is not a positive integer. It may even be, but there are no guarantees. Of course, you can check before and only after you make sure the conversion will be successful do, but it does not seem to be making sure of this. The negative would even generate an error.
  • The use of the unlabeled types should be restricted to the low level to communicate with the operating system or other language that requires the data to be so. There are a number of implications in its use that are not easy to hit. Only use it when you have complete command of computing.

Probably has a better solution to the problem. But if you still want to insist on this you need to answer a question:

What behavior do you expect to have to convert a data to a decimal part? Should it truncate or round off?

If you need to round with your own criteria you have to do it on the hand before.

You can either convert with the correct method the way you were doing, or you can use a simple cast that works fine as long as you want to truncate or know you can never have a value with decimal part.

using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        var x = 15.7M;
        WriteLine(ToUInt16(x));
        WriteLine((ushort)x);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

    
01.02.2018 / 16:29
3

There is a specific function for conversion into ushort which is Convert.ToUInt16 () . Try this:

static void Main(string[] args)
{
   decimal value= 15;
   //Nao é possivel converter, pergunta se existe uma conversao explicita...
   ushort newValue = Convert.ToUInt16(value);

   Console.WriteLine(newValue);
   Console.ReadKey();
}
    
01.02.2018 / 15:21
2

You can use (ushort) :

decimal value= 15;
ushort newValue = (ushort)value;
    
01.02.2018 / 16:39