-1

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.

Waqas Raja
  • 10,802
  • 4
  • 33
  • 38

4 Answers4

5

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));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • basically I want the result in a positive number – Waqas Raja May 02 '13 at 16:27
  • @WaqasRaja: But the result *isn't* a positive number! Do you really want `production=0, expense=5000` to have the same result as `production=5000, expense=0`? That sounds *very, very* odd. – Jon Skeet May 02 '13 at 16:28
  • actually it is the part of a complex formula, and I need the result of subtraction as a positive number – Waqas Raja May 02 '13 at 16:29
  • @WaqasRaja: You didn't answer the question - do you *really* want the results of those two very different situations to be the same? If so, see my edit and use `Math.Abs`. But that seems very unlikely to be appropriate. Fundamentally, the result of subtracting 5000 from 0 *isn't* a positive number. It just isn't. Now, what result did you want from this, and why? – Jon Skeet May 02 '13 at 16:31
0

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);
arunlalam
  • 1,838
  • 2
  • 15
  • 23
0

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.

HCL
  • 36,053
  • 27
  • 163
  • 213
0

use

var result = Decimal.ToInt64(production - expense);
Sam Leach
  • 12,746
  • 9
  • 45
  • 73