How to format a decimal in MVC3 with more than two decimal places

I have an object that is managed by the WCF service, so the entity is generated through a service link, so I cannot annotate it to indicate the data format. It is decimal and must be formatted with 6 decimal places. How can I do this in MVC3, on the display and in the editor?

On display I could use

@Html.Display(format("{0:f4}", model.MyField)) 

He is not very elegant, but he is efficient. But how can I do this to format an editor with four decimal places?

EDIT:

I found this answer to a similar question, but it gives me an error in the line

 return html.TextBox(name, value, htmlAttributes); 

Any idea how to solve it?

thanks

+4
source share
2 answers

I managed to do it as follows:

  • For display, I used

     @string.Format("{0:f4}", Model.KPINumber) 
  • for editing I used

     @Html.TextBox("KPINumber", string.Format("{0:f4}", Model.KPINumber)) 
+3
source

The syntax is simpler here:

 @Html.Display(model.MyField.ToString("f4")) 

If you want to display it in an editable text field, you can do the same:

 @Html.TextBox("myField", model.MyField.ToString("f4")) 

Obviously, this does not enforce 4 decimal places on the client side, but initially displays it with 4 decimal places.

[Edit] : in response to your edit: The answer to this question is accepted, obviously not compiled, and comments indicate this too.
Take a look at Gaz's answer because it fixes compilation errors and looks like it works.

+3
source

Source: https://habr.com/ru/post/1380871/


All Articles