Need a custom currency format to use with String.Format

前端 未结 5 665
無奈伤痛
無奈伤痛 2021-01-04 05:55

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:

相关标签:
5条回答
  • 2021-01-04 06:09

    The "C" currency formats are great until you need a blank for 0. Here are two ways, one mentioned above, similar to the ones that I use that give you the blank for 0:

    // one way
    string.Format("{0:$#,##0.00;($#,##0.00);''}", somevalue)
    
    // another way
    somevalue.ToString("$#,##0.00;($#,##0.00);''")
    

    The second technique feels more "fluent", if you like that style of code (as I do).

    0 讨论(0)
  • 2021-01-04 06:11

    Here's a great reference that you might find useful, which summarises this data: http://blog.stevex.net/string-formatting-in-csharp/

    0 讨论(0)
  • 2021-01-04 06:22

    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.

    0 讨论(0)
  • 2021-01-04 06:25

    Try something like this:

    String currency = (number == 0) ? String.Empty : number.ToString("c");
    
    0 讨论(0)
  • 2021-01-04 06:29

    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");
    }
    
    0 讨论(0)
提交回复
热议问题