Decimal.ToUInt64“对于UInt64,值太大或太小 [英] Decimal.ToUInt64 "Value was either too large or too small for a UInt64

查看:1125
本文介绍了Decimal.ToUInt64“对于UInt64,值太大或太小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做--

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.

谢谢!

无论如何,我希望结果为正数.

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

推荐答案

问题:-5000m是负数,超出了UInt64( unsigned 类型)的范围.

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

解决方案:如果要处理负数,请使用Int64而不是UInt64.

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

请注意,您可以直接投射而不是调用Decimal.To...:

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

这篇关于Decimal.ToUInt64“对于UInt64,值太大或太小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆