11

How to display the model decimal field with 3 decimal places. Currently it shortens it to 2 digits.

1,237 currently will be displayed as 1,24 ;)

svick
  • 236,525
  • 50
  • 385
  • 514
Jannik
  • 2,310
  • 6
  • 32
  • 61
  • Does this answer your question? [MVC3 Decimal truncated to 2 decimal places on edit](https://stackoverflow.com/questions/5428289/mvc3-decimal-truncated-to-2-decimal-places-on-edit) – drzaus Dec 23 '21 at 22:03

1 Answers1

20

You can use Data Annotations on your View Model, like this:

[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal Num { get; set; }
Artless
  • 4,522
  • 1
  • 25
  • 40
  • 1
    Is there a way to do it without changing the model? – Jannik Apr 26 '13 at 11:04
  • 1
    You shouldn't be using your Model in the view. You should use ViewModels instead. – Artless Apr 26 '13 at 11:07
  • So I have to write a ViewModel, even if I need exactly the things I get from the model itself? What should it look like? I want to post all model data I get from the view to the db and dont want to copy all fields to the model again... – Jannik Apr 26 '13 at 11:21
  • 3
    Yes, that would be the correct way to do it. You Model belongs to your application's Business Logic, not UI. Let's say that tomorrow you will decide to make a mobile app that will interface with your BL via WebAPI. Different UI rules will apply, and none of them are relevant to your actual data. In your question you want to change the **display** of some property, not your actual data. Your Model shouldn't be aware of it. That's where VMs come in. – Artless Apr 26 '13 at 11:28
  • 1
    How has my viewmodel to look like, so that I dont have to paste the data into the business logic model? Would deriving it from the normal model or something like that work? – Jannik Apr 26 '13 at 11:31
  • 3
    Well, you could try [Auto Mapper](http://www.codeproject.com/Articles/61629/AutoMapper). Though assigning VM -> Model values isn't all that bad, to be honest. – Artless Apr 26 '13 at 11:43