Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round to two decimal places in a string? [duplicate]

Tags:

c#

asp.net

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.

like image 925
Sankar M Avatar asked Aug 16 '11 10:08

Sankar M


People also ask

How do you round a string to 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 %.

How do you make a double to two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

Can you round a whole number to 2 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).


2 Answers

Math.Round(Convert.ToDecimal(strTemp), 2);
like image 181
CrazyMPh Avatar answered Sep 29 '22 19:09

CrazyMPh


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);  
like image 24
Anders Forsgren Avatar answered Sep 29 '22 18:09

Anders Forsgren