0

I have a variable, DifferenceAmt, which is a decimal. It can be either negative or positive. I need to output the value of DifferenceAmt, but without the negative sign if it's negative, as a string. I know how to delete the negative sign by checking first if DifferenceAmt is less than zero, and then doing a substring from the 2nd character if it is, but this seems cumbersome. I've tried converting DifferenceAmt to a UInt64 first,

UInt64 differenceamt = (UInt64)DifferenceAmt;

but I keep getting an error message that the number is too big for a UInt64 (even when it's -10, for example). How can I do this?

Melanie
  • 3,021
  • 6
  • 38
  • 56

4 Answers4

4

There are multiple available ways to do it. The simplest way is to use absolute value using Math.Abs.

decimal x = -10.53m;
string s = Math.Abs(x).ToString(); // 10.53

Another way is to use custom NumberFormatInfo with empty NegativeSign.

decimal x = -10.53m;
string s = x.ToString(new NumberFormatInfo { NegativeSign = string.Empty }); // 10.53

One more way is to use custom formatter for positive/negative numbers. But you have to specify custom string format in such case. More on this: The ";" Section Separator.

decimal x = -10.53m;
string s = x.ToString("#.##;#.##") // 10.53
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
3

Use Math.Abs(DifferenceAmt).ToString(); This will give you the absolute value of the number and remove the negative sign.

Jesse Petronio
  • 693
  • 5
  • 11
3

Use Math.Abs(differenceAmt) to get the absolute value.

Casting to UInt64 won't work. Your example of -10 is outside the range of UInt64, and it would similarly fail for other Decimal values outside the range of UInt64. It would also have to truncate the value to an integer.

pmcoltrane
  • 3,052
  • 1
  • 24
  • 30
2

You can use this:

Math.Abs(differenceAmt).ToString();

see this:

http://msdn.microsoft.com/en-us/library/a4ke8e73(v=vs.110).aspx

Brandon
  • 645
  • 5
  • 13
m.Khaki
  • 73
  • 3
  • 13