Thursday, March 22, 2012

Roundoff in string.Format

Hi friends,
   
One common task in string formatting is rounding off the fraction to a certain number of places. Lets say 3 places
The answer is simple:

double d = 2.3456;
string strFormat = string.Format("{0:f3}", d);

If you have the no. of places stored in a variable then it would look like this:
string strFormat = string.Format("{0:f" + iNumPlaces + "}", d);

No comments: