Decimal.ToUInt64 "Value was either too large or to

2019-09-27 02:52发布

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.

4条回答
Deceive 欺骗
2楼-- · 2019-09-27 03:11

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));
查看更多
冷血范
3楼-- · 2019-09-27 03:23

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楼-- · 2019-09-27 03:24

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);
查看更多
Bombasti
5楼-- · 2019-09-27 03:30

use

var result = Decimal.ToInt64(production - expense);
查看更多
登录 后发表回答