TextBoxFor decimal

In my database, I have stored fields with a datatype decimal

. I am using exactly the same type ( decimal

) in my ASP.NET application.

This is inside my view to display the value.

@Html.TextBoxFor(model => model.Stock, new { id = "Stock", @class = "k-textbox" })

      

It's pretty straight forward. The only problem I am having is that by default, in my opinion, the data is displayed with 4 decimal places.

I give you some examples of how this looks and how it should look:

  • 1.0000 => 1
  • 1.2000 => 1.2
  • 1.4300 => 1.43
  • 1.8920 => 1.892
  • 1.5426 => 1.5426

As you can see, I want to disable everything 0

as decimal places (only when displayed in the view).

Remember: I am using commas instead of decimal points.

Edit:

My model

public class Article
{
    public decimal? Stock{ get; set; }
}

      

+3


source to share


3 answers


You can use {0:G29}

like this:

@{
    string temp = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
    @Html.TextBoxFor(model => temp)
}

      

Or with string interpolation:

@{
    string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
    @Html.TextBoxFor(model => temp)
}

      



EDIT: The reason why you can't get the value in yours Controller

after you save it is because the model linker can't find a property named temp

. You can use TextBox

instead TextBoxFor

to solve this problem like this:

string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBox("Stock" , temp)

      

Or, if you still want to use TextBoxFor

, you can simply rename the variable temp

to Stock

:

string Stock = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => Stock)

      

+2


source


The G29

method argument string.Format

does exactly what you want.

You can use the following attribute for your models Stock

.

[DisplayFormat(DataFormatString = "{0:G29}", ApplyFormatInEditMode = true)]

      



Or you can use the overload mentioned by @Chris.

@Html.TextBoxFor(model => model.Stock, "{0:G29}", new { id = "Stock", @class = "k-textbox" })

      

+3


source


There is an overloadTextBoxFor

that takes a parameter format

that it uses to format the text.

This will allow you to format your number in any way you want.

+1


source







All Articles