Click here to Skip to main content
15,914,010 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am Rounding a decimal number e.g. 44.599521 to 3 digits

result will be : 44.6

but i want result in the format : 44.600

is there any built in function for the required result or i have to do it programmatically.

Thanks.
Posted

If a string output is ok for you then this will work for you.

double num = 44.599521;<br />
CultureInfo ci = new CultureInfo("myCulture");<br />
ci.NumberFormat.NumberDecimalDigits=3;<br />
string s = num.ToString("N", ci);
 
Share this answer
 
First of all, sorry. I am not a c# programer, but I had the same problem time ago and I found no built-in function. So I programmed my own function to do that. Here is what I did.

CString CMyDoc::RoundToNDecimals (double dValue, const int nDec)
{	double dTemp = 0, dFract = 0, dInt = 0, dRes = 0;
	// Operations to round up the nth decimal number if necessary
	dTemp = dValue*pow(10,nDec);
	dFract = modf (dTemp, &dInt);
	if (dFract >= 0.5)
		dInt++;
	dRes = dInt/pow(10,nDec);
        // Giving a variable string according to number and desired decimals as result
	CString szResult;
	szResult.Format ("%s%f", szResult, dRes);
	int nLarge = szResult.GetLength ();
	for (int i = 0; i < nLarge; i++)
	{	nCount++;
		CString cLetter = szResult.GetAt (i);
		if (cLetter == ".")
		{	nCount += nDec;
			break;
		}
	}
	// Truncate the string to be placed in the screen
	LPTSTR pStr = szResult.GetBufferSetLength (nCount);
	szResult.ReleaseBuffer ();

	return szResult;
;
}


I hope it helps you

Edit: I think there is no way to put 44.600 in number format, zeros at the right in decimal numbers are not considered.

Edit_2: Best answer in required language above... forget this one
 
Share this answer
 
v4
I prefer this way:

double val = 44.599521;
string formattedValue = String.Format("{0:#.000}", val);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900