C#中如何将数字四舍五入到小数点后两位?
我想使用 Math.Round 函数来完成此操作
I want to do this using the Math.Round
function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我想使用 Math.Round 函数来完成此操作
I want to do this using the Math.Round
function
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(17)
字符串a =“10.65678”;
小数 d = Math.Round(Convert.ToDouble(a.ToString()),2)
string a = "10.65678";
decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)
这是一个老问题,但如果您使用 C# 6 或更高版本并希望将数字显示为小数点后 2 位,您可以使用插值字符串并在带冒号的表达式后面指定格式字符串:
var myStringNumber = $"{Math .Round(myDoubleNumber, 2):0.00}";
It's an old question but if you're using C# 6 or above and want to display the number to 2 decimal places, you can you use interpolated strings and specify a format string after an expression with a colon :
var myStringNumber = $"{Math.Round(myDoubleNumber, 2):0.00}";
以下是一些示例:
您可能还想查看具有以下重载的银行家四舍五入/四舍五入:
有更多信息此处。
Here's some examples:
You might also want to look at bankers rounding / round-to-even with the following overload:
There's more information on it here.
尝试这个:
Try this:
如果您想要一个字符串
或小数
但请记住! 舍入不具有分配性,即。
round(x*y) != round(x) * round(y)
。 因此,在计算结束之前不要进行任何舍入,否则您将失去准确性。If you'd like a string
Or a decimal
But remember! Rounding is not distributive, ie.
round(x*y) != round(x) * round(y)
. So don't do any rounding until the very end of a calculation, else you'll lose accuracy.就我个人而言,我从不舍弃任何东西。 尽可能保持坚定,因为无论如何,四舍五入在 CS 中有点转移注意力。 但您确实希望为用户设置数据格式,为此,我发现
string.Format("{0:0.00}", number)
是一个很好的方法。Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that
string.Format("{0:0.00}", number)
is a good approach.维基百科有一个关于一般舍入的很好的页面。
所有 .NET(托管)语言都可以使用任何公共语言运行时 (CLR) 舍入机制。 例如,Math.Round() (如上所述)方法允许开发人员指定舍入类型(舍入到偶数或远离零)。 Convert.ToInt32() 方法及其变体使用 round-to-even< /a>. Ceiling() 和 Floor() 方法是相关的。
您也可以使用自定义数字格式进行舍入。
请注意 Decimal.Round() 使用与 Math.Round() 不同的方法;
这是关于银行家的有用的帖子舍入算法。
请参阅 Raymond 此处的一篇关于舍入的幽默帖子。 。
Wikipedia has a nice page on rounding in general.
All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.
You can round with custom numeric formatting as well.
Note that Decimal.Round() uses a different method than Math.Round();
Here is a useful post on the banker's rounding algorithm.
See one of Raymond's humorous posts here about rounding...
// 最多转换两位小数
=========
也可以将“0”与“#”组合起来。
// convert upto two decimal places
=========
can also combine "0" with "#".
如果要对数字进行舍入,您可以获得不同的结果,具体取决于: 如何使用 Math.Round() 函数(如果用于向上舍入或向下舍入)、您正在使用双精度数和/或浮点数,然后应用中点舍入。 特别是,当与其中的操作一起使用或要舍入的变量来自操作时。 假设您想要将这两个数字相乘:0.75 * 0.95 = 0.7125。 正确的? 不在 C# 中
让我们看看如果您想四舍五入到小数点后第三位会发生什么:
如您所见,如果您想向下舍入中点,第一个 Round() 是正确的。 但是第二个 Round() 如果你想向上取整,那就错了。
这适用于负数:
因此,恕我直言,您应该为满足您的要求的 Math.Round() 创建自己的包装函数。 我创建了一个函数,其中参数“roundUp=true”表示四舍五入到下一个更大的数字。 即:0.7125 舍入为 0.713,-0.7125 舍入为 -0.712(因为 -0.712 > -0.713)。 这是我创建的函数,适用于任意位数的小数:
变量“校正器”用于修复浮点数或双精度数运算的不准确性。
If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.
这是为了在 C# 中四舍五入到小数点后两位:
在 VB.NET 中:
This is for rounding to 2 decimal places in C#:
In VB.NET:
我知道这是一个老问题,但请注意数学回合和字符串格式回合之间的以下差异:
I know its an old question but please note for the following differences between Math round and String format round:
有一个奇怪的情况,我有一个十进制变量,当序列化 55.50 时,它总是将数学上的默认值设置为 55.5。 但是,由于某种原因,我们的客户端系统认真地期望 55.50,并且他们肯定期望小数。 就在那时,我编写了下面的帮助程序,它总是将任何用零填充的十进制值转换为 2 位数字,而不是发送字符串。
用法应该是
输出:
Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.
Usage should be
Output:
只需
Math.Round()
即可解决此问题,并通过向该方法传递precision
参数和MidpointRounding
参数来适应情况。默认情况下,Math.Round 使用 MidpointRounding.ToEven,这实际上是银行家舍入,意味着中间的数字舍入到最接近的偶数:
让我做一下很清楚。 实际上,您可以采用 5 种
MidpointRounding
策略来获得Math.Round()
的预期结果:ToEven(默认) 当一个数字介于另外两个数字之间时,它会向最接近的偶数舍入。
AwayFromZero(数学舍入) 当一个数字介于其他两个数字之间时,它会向远离零的最接近的数字舍入。 (又名,四舍五入)
ToZero 根据指定精度对数字进行向下舍入
ToNegativeInfinity (floor) 根据指定精度对数字进行向下舍入
ToPositiveInfinity(上限) 根据指定精度对数字进行向上舍入。
下面是查看它们如何工作的代码:
结果:
Simply
Math.Round()
solves this problem and fits the situation by passing aprecision
parameter andMidpointRounding
parameter to the method.By default
Math.Round
usesMidpointRounding.ToEven
which is actuallybankers rounding
meaning that the halfway numbers round to the nearest even number:Let me make it clear. Actually, there are 5 strategies of
MidpointRounding
you could take to get what you expect fromMath.Round()
:ToEven (default) When a number is halfway between two others, it is rounded toward the nearest even number.
AwayFromZero (mathematical rounding) When a number is halfway between two others, it is rounded toward the nearest number away from zero. (Aka, round up)
ToZero rounds down the number based on specified precision
ToNegativeInfinity (floor) rounds down the number based on specified precision
ToPositiveInfinity (ceiling) rounds up the number based on specified precision.
Here is the code to see exactly how they work:
the result:
您可能需要检查的一件事是 Math.Round 的舍入机制:
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
除此之外,我建议使用 Math.Round(inputNumer, numberOfPlaces) 方法而不是 *100/100 方法,因为它是清洁工。
One thing you may want to check is the Rounding Mechanism of Math.Round:
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.
您应该能够使用 Math.Round(YourNumber, 2) 指定要舍入的位数。
您可以阅读更多内容 此处。
You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)
You can read more here.
数学底线(123456.646 * 100) / 100
将返回 123456.64
Math.Floor(123456.646 * 100) / 100
Would return 123456.64