views:

87

answers:

3

If I have a decimal, how do I get a string version of it with two decimal places? This isn't working:

Math.Round(myDecimal, 2).ToString("{0.00}");
+7  A: 

Don't use the curly brackets, they are for embedding a formatted value in a longer string using string.Format. Use this:

myDecimal.ToString("0.00");
David M
Note that the format string `"{0.00}"` wouldn't work for `string.Format` either; you'd have to use `"{0:0.00}"` there.
Joey
+2  A: 

Maybe i'm wrong, but i've tried myDecimal.ToString(); and it worked.

Gabriel
+1 : Unlike `float` and `double`, the `decimal` data type will retain the number of digits of precision, so `Math.Round(myDecimal, 2).ToString();` should work just fine. No format string required.
Jeffrey L Whitledge
A: 

Assuming myDecimal is a System.Decimal, then Math.Round(myDecimal, 2).ToString(); will display two decimal digits of precision, just as you want, without any format string (unless the absolute value of your number is greater than 10^27-1). This is because the decimal datatype retains full precision of the number. That is to say that 1m, 1.0m, and 1.00m are all stored differently and will display differently.

Note that this is not true of float or double. 1f, 1.0f, and 1.00f are stored and display identically, as do 1d, 1.0d, and 1.00d.

Since the format string must be parsed at runtime, I would probably omit it for code like this in most cases.

Jeffrey L Whitledge