Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
string strTemp = "0.51667308807373";
convert to decimal by rounding of two decimal places.
String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
If we want to round 4.732 to 2 decimal places, it will either round to 4.73 or 4.74. 4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74).
Math.Round(Convert.ToDecimal(strTemp), 2);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With