Decimal.ToUInt64 "Value was either too large or too small for a UInt64

此生再无相见时 提交于 2019-12-13 09:44:22

问题


I am doing: -

Decimal production = 0;
Decimal expense = 5000;

Decimal.ToUInt64(production - expense);

But it throws exception with the following error message.

"Value was either too large or too small for a UInt64"

Can someone give me a workaround for this.

Thanks!

Edit

In any case, I want the result as a positive number.


回答1:


Problem: -5000m is a negative number, which is outside the range of UInt64 (an unsigned type).

Solution: use Int64 instead of UInt64 if you want to cope with negative numbers.

Note that you can just cast instead of calling Decimal.To...:

long x = (long) (production - expense);

Alternative: validate that the number is non-negative before trying to convert it, and deal with it however you deem appropriate.

Very dodgy alternative: if you really just want the absolute value (which seems unlikely) you could use Math.Abs:

UInt64 alwaysNonNegative = Decimal.ToUInt64(Math.Abs(production - expense));



回答2:


0 - 5000 will return -5000. And you are trying to convert to an unsigned int which can not take negative values.

Try changing it to signed int

Decimal.ToInt64(production - expense);



回答3:


UInt can not store negative numbers. The result of your calculation is negative. That's why the error comes. Check the sign before using ToUInt64 and correct it via *-1 or use a signed Int64.




回答4:


use

var result = Decimal.ToInt64(production - expense);


来源:https://stackoverflow.com/questions/16343018/decimal-touint64-value-was-either-too-large-or-too-small-for-a-uint64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!