bzamfir
bzamfir

Reputation: 4886

How to format decimal in MVC3 with more than 2 decimals

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

Upvotes: 4

Views: 10817

Answers (2)

Scott Rippey
Scott Rippey

Reputation: 15810

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.

Upvotes: 3

bzamfir
bzamfir

Reputation: 4886

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))
    

Upvotes: 3

Related Questions