Convert decimal to ushort

Asked

Viewed 100 times

1

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

Is there such a possibility?

If yes, how to convert?

I tried to use the Convert.ToInt16(value), but it didn’t work.

Console example:

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();
}

3 answers

3

There is a specific function for conversion into ushort which is the Convert.Touint16(). Try it like 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();
}

3


Essentially I shouldn’t be doing this for two reasons:

  • It is probably losing data since a decimal is not a positive integer. It may be, but there are no guarantees. Of course, you can check before and only after you are sure that the conversion will be successful to do, but it does not seem to be making sure of this. The negative would even generate error.
  • The use of unmarked 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 to its use that are not easy to get right. Only use it when you have complete mastery of computation.

You probably have a better solution to the problem. But if you still want to insist on this you need to answer a question:

How do you expect to convert a data to a decimal part? You should truncate or round?

If you need to round at your own discretion you have to do it in the hand first.

You can have it converted with the right method, the way you were doing, or you can use a simple cast which in this case works well, as long as you want the truncation or know that you can never have a decimal part value.

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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

2

You can use (ushort):

decimal value= 15;
ushort newValue = (ushort)value;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.