Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBoxFor decimal

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. 1,0000 => 1
  2. 1,2000 => 1,2
  3. 1,4300 => 1,43
  4. 1,8920 => 1,892
  5. 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; }
}
like image 452
Tom el Safadi Avatar asked Jul 12 '17 13:07

Tom el Safadi


3 Answers

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" })
like image 67
NtFreX Avatar answered Nov 13 '22 12:11

NtFreX


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)
like image 43
Salah Akbari Avatar answered Nov 13 '22 14:11

Salah Akbari


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.

like image 37
Chris Avatar answered Nov 13 '22 14:11

Chris