将十进制数字四舍五入为固定数字和固定长度

编程入门 行业动态 更新时间:2024-10-18 14:18:45
本文介绍了将十进制数字四舍五入为固定数字和固定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要舍入一个十进制数字,例如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);

更多推荐

将十进制数字四舍五入为固定数字和固定长度

本文发布于:2023-11-10 02:42:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度   四舍五入   数字   十进制数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!