How to round to two decimal places in a string?

Math.Round(Convert.ToDecimal(strTemp), 2);

Convert the value to a floating point number, then round it:

double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
temp = Math.Round(temp, 2);

Alternatively, if you want the result as a string, just parse it and format it to two decimal places:

double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
string result = temp.ToString("N2", CultureInfo.InvariantCulture);

Note: The CultureInfo object is so that the methods will always use a period as decimal separator, regardless of the local culture settings.


First convert string to decimal (Using Decimal.Parse or Decimal.TryParse).

decimal d = Decimal.Parse("123.45678");

Then round the decimal value using Round(d, m) where d is your number, m is the number of decimals, see http://msdn.microsoft.com/en-us/library/6be1edhb.aspx

decimal rounded = Decimal.Round(d, 2); 

If you only want to round for presentation, you can skip rounding to a decimal and instead simply round the value in output:

string.Format("{0:0.00}", 123.45678m);  

Tags:

C#

Asp.Net