Need a custom currency format to use with String.Format

亡梦爱人 提交于 2019-11-30 17:37:19

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.

Try something like this:

String currency = (number == 0) ? String.Empty : number.ToString("c");

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!