Archive for August, 2016

Formatting a double as a decimal in MVC

Pretty simple to do using a DisplayFormat attribute on the property you are trying to format:

[DisplayFormat(DataFormatString = "{0:0.0}", ApplyFormatInEditMode = true)]
public double Hours { get; set; }

My initial attempt failed because I was using the String.Format nation of {0:0N}, which didn’t work.

You can also using String.Format in the view to format the decimal into a string. In the example below, “item.Rate” is a double that I wanted to format to two decimal places, regardless of length:

@String.Format(“{0:0.00}”, item.Rate)


Leave a comment