Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...