8

I'm looking for a DataFormatString that will display a float as a currency. But omit the decimal values if they're irrelevant (0's).

At the moment I'm using:

[DisplayFormat(DataFormatString = "{0:C}")]

On my models. This is displaying as a currency correctly. I've not been able to find anywhere that details what changes I need to make to omit the decimal places?

crthompson
  • 15,653
  • 6
  • 58
  • 80
Ben Ford
  • 1,354
  • 2
  • 14
  • 35
  • possible duplicate of [Currency Formatting MVC](http://stackoverflow.com/questions/10741190/currency-formatting-mvc) – 123 456 789 0 Nov 05 '13 at 22:21
  • 2
    I don't think this is a duplicate. The link above shows a solution describing what the OP of this question is already using. It doesn't address his question regarding omitting the decimal values if they are irrelevant. – mayabelle Nov 05 '13 at 22:31

3 Answers3

10
[DisplayFormat(DataFormatString = "{0:C0}")]

This should give you 0 decimals. But automatically rounds! so if you got ,56 it will round up to 1

20000,00 => 20000 €

20000,56 => 20001 €

20000,49 => 20000 €

/edit: I have borrowed an idea from here: c# Decimal to string for currency

If you can convert your float value to decimal, you can use this Extensionmethod to omit the 0. It truncates the decimal and if this truncated value is equal to the original value, it cuts the zeros. If not, it displays 2 digits. I know this is no Dataformat string, but I'm not quiet sure, it can be done in an as simple way as an annotation.

public static string ToCurrencyString(this decimal d)
{
    return d.Equals(Decimal.Truncate(d)) ? d.ToString("0 €") : d.ToString("0.00 €");
}
Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
3

I don't think there is a way to do it that explicitly uses currency formatting, but you can use custom formatting using the # character: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

This should work for U.S. currency:

[DisplayFormat(DataFormatString = "{0:$#.##}")]

The # character only represents a digit if it's needed.

mayabelle
  • 9,804
  • 9
  • 36
  • 59
0
var price = 100.0M;
var curr = price % 1 == 0 ? price.ToString("C0") : price.ToString("C");

You can put this in an extension method and call it where you need it.

NeutronCode
  • 365
  • 2
  • 13