Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - 3 decimal places on type double with leading zero

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. In display view I would like the Kgs to appear like 560.250

Trying to learn MVC3 + Razor. Willing to explore JQuery, use of regular expressions, validators, view templates, view models...

The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.

Thank you in advance for your help.

like image 562
Par6 Avatar asked Sep 11 '11 01:09

Par6


People also ask

What is zero decimal point?

Accuracy and Scientific Notation If there is no decimal point, it is understood to be after the last digit on the right and there is no place (zero place) accuracy. The significant digits of a number are those digits that are most accurate.

How do I format a string to two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


2 Answers

You could use data annotations on your view model:

[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }

and in your view

@Html.EditorFor(x => x.Weight)

will properly format the value in the input field.

Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):

@model double?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")

and then in your view:

@Html.EditorFor(x => x.Weight)

or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:

@Html.EditorFor(x => x.Weight, "MyFormattedDouble")

Personally I prefer the first approach which uses data annotations to control the format of the double values.

like image 53
Darin Dimitrov Avatar answered Sep 27 '22 21:09

Darin Dimitrov


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.

like image 22
Joseph Shanak Avatar answered Sep 27 '22 19:09

Joseph Shanak