5

I want after decimal point only 2 digit.

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

Need output like this:

56.23

456.20

1.21

like that..

4

5 回答 5

3

I would use editor templates in my views. I would define view models which are specifically tailored to the requirements of the given view (in this case limiting it to 2 decimals):

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

or You can simply use regular expression with model like

[RegularExpression(@"^\d+.\d{0,2}$")]
public decimal Viewers{ get; set; }

and then in html:

@Html.EditorFor(m => m.Viewers) 

or TextBoxFor()will also work with regular expression

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })
于 2016-11-18T11:46:42.277 回答
2

In View

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 }, new { Value=String.Format("{0:0.##}",Model.Viewers) })

In controller also you can format your String.Format("{0:0.##}",Object.viewers)

Object- Means model(contains field Viewers) which is passed to View

Hope this is helpful

于 2016-11-18T11:45:44.960 回答
1

I suggest you to format your decimals on client side like this:

In your ViewModel:

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

And on your View use EditorFor:

 @Html.EditorFor(m => m.Viewers, new { @tabindex = 7 })

When this value posts to your Controller just trim it to 2 nums.

If you need validation use Regex:

[RegularExpression(@"^\d+\.\d{0,2}$")] //this line
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal Viewers { get; set; }
于 2016-11-18T11:45:30.927 回答
1

If I use.

String.Format("{0:0.00}", 123.4567);     

So result:

 // "123.46"

So you can try this

@Html.TextBoxFor(m => String.Format("{0:0.00}", m.Viewers) , new { @tabindex = 7 })
于 2016-11-18T11:51:29.913 回答
0

  $("#Viewers").change(function (e) {

            var num = parseFloat($(this).val());
            $(this).val(num.toFixed(2));
});
   @Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

Thank you for all to reply me !!! :)

于 2016-11-18T13:07:12.717 回答