Search code examples
c#asp.net-mvcasp.net-mvc-2string-formattingstrongly-typed-view

String Formatting in C# for Strongly typed view


I want to know how can I convert a strong typed view Price field in to 2 digit specifier like i have got a money field in my db which converts for instance 15 into 15.0000 , i juts want to display 15.00 in the view , below is the code:

<%: Html.TextBoxFor(model =>model.Price, new { maxlength = "5", style = "width:40px;" })%>

I tried something like with no success:

<%: Html.TextBoxFor(model => String.Format("{0:n}"model.Price), new { maxlength = "5", style = "width:40px;" })%>

Solution

  • Try this:

    <%: Html.TextBoxFor(model => model.Price.ToString("0.00"), new { maxlength = "5", style = "width:40px;" })%>
    

    Update:

    You also missed a comma in your original syntax which could be all that's stopping it from working that way too. Should have been:

    <%: Html.TextBoxFor(model => String.Format("{0:n}", model.Price), new { maxlength = "5", style = "width:40px;" })%>
    

    Also, for 2 decimal places, try it like this:

    <%: Html.TextBoxFor(model => String.Format("{0:0.00}", model.Price), new { maxlength = "5", style = "width:40px;" })%>