31

I have a decimal value for example: 59625879,00

I want to show this value like this: 59.625,879 or 59625,879

How can I do this with @Html.DisplayFor(x => x.TAll, String.Format()) ?

Thanks.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

1 Answers1

86

Decorate your view model property with the [DisplayFormat] attribute and specify the desired format:

[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public decimal TAll { get; set; }

and then in your view:

@Html.DisplayFor(x => x.TAll)

Another possibility if you don't want to do this on the view model you could also do it inside the view:

@Model.tAll.ToString("N")

but I would recommend you the first approach.


Yet another possibility is to write a custom display template for the decimal type (~/Views/Shared/DisplayTemplates/MyDecimalTemplate.cshtml):

@string.Format("{0:N}", Model)

and then:

@Html.DisplayFor(x => x.TAll, "MyDecimalTemplate")
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is it possible to do this at view side, not with model? – AliRıza Adıyahşi Aug 22 '12 at 06:33
  • No, I never said to do this on the model. You misunderstood my answer. I said to do this on the view model. – Darin Dimitrov Aug 22 '12 at 06:34
  • `DisplayFor` helper has paramater that is called `string TemplateName`. Could not I use this property to do this? – AliRıza Adıyahşi Aug 22 '12 at 06:38
  • @DarinDimitrov I have int? property in model and when I use first approach it works in `DisplayFor` but `EditorFor` is empty, and one question how can i change value of the property like I have int? with value of 150 and I'd like to display 1.50 – pepela Feb 27 '14 at 12:57
  • 2
    For anyone who landed on this (correct and good) answer but wants to know how else they can adjust the display format, check this link https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring(v=vs.110).aspx – Giovanni B Mar 13 '18 at 17:36
  • Had to use `{0:N0}` in `[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]` – devlin carnate Aug 28 '19 at 21:33