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..

teo van kot
  • 12,350
  • 10
  • 38
  • 70
lashja
  • 493
  • 10
  • 21

5 Answers5

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 })
Fuzzybear
  • 1,388
  • 2
  • 25
  • 42
MANISH KUMAR CHOUDHARY
  • 3,396
  • 3
  • 22
  • 34
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

J-Mean
  • 1,192
  • 1
  • 8
  • 14
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; }
teo van kot
  • 12,350
  • 10
  • 38
  • 70
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 })
  • "HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." - got error like this. – lashja Nov 18 '16 at 12:09
  • 1
    try rebuild this is not Html code error please check help for this error here. https://support.microsoft.com/en-us/kb/942041 –  Nov 18 '16 at 12:11
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 !!! :)

lashja
  • 493
  • 10
  • 21