将十进制数字四舍五入为固定数字和固定长度 [英] Rounding a decimal number to fixed number and fixed length
本文介绍了将十进制数字四舍五入为固定数字和固定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要舍入一个十进制数字,例如44.599521至 3 个数字
结果将是:44.6
但我想要的结果格式为:44.600
是否有任何用于所需结果的内置函数,或者我必须以编程方式进行.
谢谢.
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.
推荐答案
如果您可以输出字符串,则对您有用.
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);
首先,对不起.我不是c#程序员,但是前段时间我遇到了同样的问题,但是我没有找到内置函数.因此,我编写了自己的函数来执行此操作.这就是我所做的.
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;
;
}
希望对您有帮助
我认为没有办法以数字格式放入44.600,不考虑十进制数字右边的零.
Edit_2:以上所需语言的最佳答案...忘记这个
I hope it helps you
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
我更喜欢这种方式:
I prefer this way:
double val = 44.599521;
string formattedValue = String.Format("{0:#.000}", val);
这篇关于将十进制数字四舍五入为固定数字和固定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文