Asked by:
How do I round a decimal to 2 decimal places?

Hello
I have this code:
while (rdr.Read())
{
gotPrice = (rdr.GetDecimal(0));
}
rdr.Close();
....but I can't work out how to properly round the result to 2 decimal places before assigning the variable gotPrice?I get this as example: 54.9700
and I'd like gotPrice = 54.97
Thanks for your time
Question
All replies


To get Decimal back use Math.Round with Second parameter specifying number of decimal points.
decimal d = 54.9700M;
decimal f = (Math.Round(d, 2)); // 54.97
Console.WriteLine(f.ToString());
To Get String representation of number use String.Format() Specifiying Fixed Points as F2
decimal d = 54.9700M;
string s = String.Format("{0:F2}", d)); // "54.97"
I hope this will Help!
Best Regards,
Updated
 Proposed as answer by Sergiu Dudnic Thursday, March 12, 2009 4:18 PM



Do you want to round the value to two decimal places or format the value with two decimal plays. If the later, using a the Decimal.ToString or the String.Format method as described by RizwanSharp. If you want to round to two decimals use Math.Round, as described by NatasataN.