Search code examples
c#doubleconvertersushort

C# convert "double" to "ushort"


I'm stuck with variables format. I know this is a stupid question but I'm on it for 2 hours and I'm losing my mind.

The problem is:

I have:

command.Data = new ushort[] { xx, yy, zz };

And I need to do:

ushort zz = System.Math.Tan(c1AngleX);

But the output of System.Math.Tan is "double", so I kinda can't have the "ushort" there.

I tried this

ushort zz = (Convert.ToUInt16 (System.Math.Tan(c1AngleX));

But it does not work. (Cannot convert "double" to "string")

There's any way to convert "double" to "ushort"?

(I'm sorry if this question is "too trivial", but I'm really stuck)


Solution

  • An ushort is a 16-bit variable that can hold whole values between 0 and 65535. A double is a 8-byte variable that can hold .. lots of values, including fractions.

    So if you convert the double to a ushort you will probably lose data. This is why the system will not let you do it without explicit instruction.

    The easiest way to cast is using the cast operators: eg

    double d = 99.99;
    ushort u = (ushort)d;
    

    or you can cast it using one of the maths functions that explicitly round or truncate the double, but they return doubles so you'll still have to cast.

    You should consider why you want to put a double value into a ushort type first. Designing for correct behaviour is far more important than squishing a round peg into a square hold just because you can.