简体   繁体   中英

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)

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.

The problem you seem to have is the fact that converting from a floating point type to an interger type will lose you the decimals.

If you do your conversion on the value 0.111333423 (let's assume that is the result of Tan) zz will have the value 0 because any decimals will be removed. And since ushort is also unsigned, the sign isn't transferred either.

There are ways to deal with decimals in integer types called fixed-point integer, for instance. But that is assuming that you really need to use ushort (or any integer type for that matter) for what ever reason. In case of such functions, you should avoid integer types due to data loss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM