Reputation: 6776
In my database I stored fields with the data type decimal
. I am using exactly the same (decimal
) data type in my ASP.NET application.
This is inside my view in order to display the value.
@Html.TextBoxFor(model => model.Stock, new { id = "Stock", @class = "k-textbox" })
This pretty straight forward. The only issue I am facing is that by default in my view the data is displayed with 4 decimal places.
I give you a few examples on how it 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 cut off all the 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; }
}
Upvotes: 5
Views: 8972
Reputation: 39956
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 that you can't get the value in your Controller
after you save it is that the model binder can't find a property with name temp
. You can use a TextBox
instead of TextBoxFor
to solve this issue like this:
string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBox("Stock" , temp)
Or if you still want to use TextBoxFor
you can just rename the temp
variable to Stock
:
string Stock = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => Stock)
Upvotes: 3
Reputation: 11357
The G29
argument of the string.Format
method does exactly what you want.
You can use the the following attribute on your models Stock
value.
[DisplayFormat(DataFormatString = "{0:G29}", ApplyFormatInEditMode = true)]
Or you can use the overload which @Chris mentioned.
@Html.TextBoxFor(model => model.Stock, "{0:G29}", new { id = "Stock", @class = "k-textbox" })
Upvotes: 8
Reputation: 27609
There is an overload of TextBoxFor
that takes a format
parameter that it uses to format the text.
This will allow you to format your number in any way you want.
Upvotes: 1