views:

2926

answers:

4

I'm trying to use String.Format("{0:c}", somevalue) in C# but am having a hard time figuring out how to configure the output to meet my needs. Here are my needs:

  1. 0 outputs to blank
  2. 1.00 outputs to $1.00
  3. 10.00 outputs to $10.00
  4. 100.00 outputs to $100.00
  5. 1000.00 outputs to $1,000.00

I've tried String.Format("{0:c}", somevalue) but for zero values it outputs $0.00 which is not what I want. I've also tried String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue), but for 1.0 it outputs $01.00. String.Format("{0:$0.00;$(0.00);#}", somevalue) works for most cases, but when somevalue is 1000.00 the output is $1000.00.

Is there some format that will fit all 5 cases above? All of the documentation I've read only details the basics and doesn't touch on this type of scenario.

+3  A: 

Try something like this:

String currency = (number == 0) ? String.Empty : number.ToString("c");
Andrew Hare
+7  A: 

If you use

string.Format("{0:$#,##0.00;($#,##0.00);''}", value)

You will get "" for the zero value and the other values should be formatted properly too.

DavGarcia
This is what I've been looking for. I'm doing this formatting in a Repeater and wanted something that was simple and concise.
Notorious2tall
Andrew's response worked too and if I were doing this in codebehind I would have gone with his solution and not even try to figure out the String.Format. But I was looking for the elegant solution. Not that anyone could have read my mind on that one. :)
Notorious2tall
+1 from me.. excellent.. could you please explain me in bit detail about how this works..
Jeeva S
When value is a number, the string format {0:A;B;C} checks if the value is positive, negative or zero. If it is positive, then A is used, negative uses B and zero uses C as the format.
DavGarcia
+1  A: 

Depending on if you are consistently using the same data type for all of your currency values, you could write an extension method that would make it so that your case is always met. For example if you were using the decimal type:

public static string ToCurrencyString (this decimal value)
{
  if (value == 0)
    return String.Empty;
  return value.ToString ("C");
}
scwagner
+1  A: 

Here's a great reference that you might find useful

Juan Manuel