21

I am trying to get @String.Format("{0:0.00}",Model.CurrentBalance) into this @Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance" })

I just want the currency to show up as .00 inside of my textbox but am having no luck. Any ideas on how I do this?

Samjus
  • 603
  • 1
  • 5
  • 24

3 Answers3

31

string.format("{0:c}", Model.CurrentBalance) should give you currency formatting.

OR

@Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • @Html.TextBoxFor(String.Format("{0:C}",model => model.CurrentBalance), new { @class = "required numeric", id = "CurrentBalance" })....Is this the style I am looking for? – Samjus Aug 05 '11 at 23:17
  • 5
    @Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })...This is what I was looking for. Thank you for the help:) – Samjus Aug 05 '11 at 23:22
  • 2
    It is worthwhile to note the currency notation is dependent on your region settings. In parts of Europe you will get `$1.000.000,00` for one million dollars, and depending on the settings you could get `($20.00)` or `-$20.00` for negatives. – Aren Aug 05 '11 at 23:32
  • Why the heck the 'v' in `Value` has to be capital? – Michal Hosala Dec 30 '15 at 11:41
  • 2
    This is a hack. It works only because "Value" takes precedence over "value". This shouldn't be the accepted answer. – user1751825 Jul 03 '19 at 16:59
  • 1
    Please use Gail Foad's answer instead. There is a parameter overload for TextBoxFor that accepts a string formatter, that is much better than calculating the format when setting it from the model. – TeaBaerd Nov 24 '21 at 18:50
22
@Html.TextBoxFor(model => model.CurrentBalance, "{0:c}", new { @class = "required numeric", id = "CurrentBalance" })

This lets you set the format and add any extra HTML attributes.

Gail Foad
  • 623
  • 10
  • 22
2

While Dan-o's solution worked, I found an issue with it regarding the use of form-based TempData (see ImportModelStateFromTempData and ExportModelStateToTempData). The solution that worked for me was David Spence's on a related thread.

Specifically:

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

Now if you use EditorFor in your view the format specified in the annotation should be applied and your value should be comma separated:

<%= Html.EditorFor(model => model.Price) %>
Community
  • 1
  • 1
cat5dev
  • 1,317
  • 15
  • 12