MVC3 - 3 decimal places on type double with leading zero

后端 未结 3 1658
萌比男神i
萌比男神i 2020-12-03 14:38

I have a field for weight in Kgs (type double or use something else??). In edit view I would like the user to enter numbers to the thousandth place<

3条回答
  •  鱼传尺愫
    2020-12-03 15:03

    To format the number just use

     @string.Format("{0:0.00}", Model.Weight);
    

    or

     @Html.DisplayFor(x => string.Format("{0:0.00}", x.Weight));
     @Html.EditorFor(x => string.Format("{0:0.00}", x.Weight));
    

    to Validate

    public class Model
    {
        [Required]
        public double Weight{ get; set; }
    }
    

    I wouldn't constrain the precision they put in, just make sure that it is a valid number using javascript. You might also constrain input to only include numbers and a period.

    If the user puts in something wrong (i.e. not compatible with a double type), MVC will complain when it tries to bind to the model.

提交回复
热议问题