10

I'm using MVC3 with a detailed view that needs to display a formatted dollar amounts like $1,200.00. The controller is passing in a double value in this case for MonthlyMortgage to the view. The line of code below however, does not display the correct string formatting. What is displayed is $1200.00, and what I need is $1,200.00.

I have tried:

$@String.Format("{0:c}", Html.DisplayFor(model => model.MonthlyMortgage))

and I have tried this:

$@String.Format("{0:#,###,###,##0.000}", Html.DisplayFor(model => model.MonthlyMortgage))

Can someone please enplane why this is not working?

Shawn
  • 509
  • 3
  • 12
  • 25
  • Could be a duplicate of this: http://stackoverflow.com/questions/890100/how-do-i-format-a-double-to-currency-rounded-to-the-nearst-dollar – Davin Tryon Jun 24 '12 at 08:11

3 Answers3

21

You don't need to use Html.DisplayFor because it will return MvcHtmlString so the string.Format doesn't apply.

Just use the string.Format on your model:

@String.Format("{0:c}", Model.MonthlyMortgage)

Note you don't need the '$' sign anymore because the {0:c} will take care of it.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • That was nice. I never thought of using the Model property directly which corrected my problem. Thanks... – Shawn Jun 24 '12 at 08:19
11

@nemesv has a direct answer. The other option would be to remove String.Format() from the View and use DataAnnotations to attach a formatting to MonthlyMortgage.

An example from MSDN:

[DisplayFormat(DataFormatString = "{0:C}")]
public Decimal ListPrice { get; set; }

And btw, #,###,###,##0.000 can be shortened to #,##0.00

H H
  • 263,252
  • 30
  • 330
  • 514
  • IMO, the best answer since I was needing to have mine in `@Html.DisplayFor(m => m.CurrencyProperty)`. – ganders Sep 26 '19 at 05:40
0

Another option is the [DataType] attribute.

Add DataAnnotations using System.ComponentModel.DataAnnotations; and using System.ComponentModel.DataAnnotations.Schema then you can do something like this in the model.

[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18, 2)")]
public decimal MonthlyMortgage{ get; set; }
smoore4
  • 4,520
  • 3
  • 36
  • 55