How to format decimal in MVC3 with more than 2 decimals

10,668

Solution 1

I managed to make it as follows:

  1. For display I used

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

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

Solution 2

Here's an easier syntax:

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

If you want to display it in an editable textbox, you could do the same:

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

Obviously, this doesn't enforce 4 decimals client-side, but it initially displays it with 4 decimals.

[Edit]: In response to your edit: That question's "accepted" answer obviously does not compile, and the comments indicate this too.
Take a look at Gaz's answer because it fixes the compile errors and looks like it works.

Share:
10,668
bzamfir
Author by

bzamfir

Updated on June 05, 2022

Comments

  • bzamfir
    bzamfir almost 2 years

    I have an entity that is managed by a WCF service, so the entity is generated through service reference so I cannot annotate it to specify data format. It is decimal and must be formatted with 6 decimals. How can I accomplish this in MVC3, in display and editor?

    In display I could use

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

    It's not very elegant, but it's workable. But how can I do this for formatting the editor with 4 decimals?

    EDIT:

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

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

    Any idea how to solve it?

    Thanks