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)

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: