[Solved] Decimal.ToUInt64 “Value was either too large or too small for a UInt64


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

4

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