简体   繁体   English

如何对数字进行舍入运算

[英]How to Make Math.Round for a Number

how to make the Rounded number ? 如何使四舍五入?

Example : 3341.48 to 3342.00 范例:3341.48至3342.00

It seems you always want to round up here. 看来您总是想在这里四舍五入。 In that case use 在那种情况下使用

Math.Ceiling(3341.48)

This will return 3342. 这将返回3342。

If you want to round towards the nearest whole number, use 如果要四舍五入到最接近的整数,请使用

Math.Round(3341.48)

This will return 3341. Note that Bankers rounding is the default setting here, that might cause some unexpected result for rounding X.50. 这将返回3341。请注意,“ Bankers rounding是此处的默认设置,这可能会导致X.50舍入的某些意外结果。

If you want 3341.48 to round up to 3342, it sounds like you might want Math.Ceiling : 如果您希望3341.48舍入到3342,这听起来像您可能想要Math.Ceiling

decimal m = 3341.48m;
decimal roundedUp = Math.Ceiling(m);

This will always round up - so 3341.0000001 would still round to 3342, for example. 这将始终四舍五入-因此,例如3341.0000001仍将舍入为3342。 If that's not what you're after, please specify the circumstances in which you want it to round up, and those in which you want it to round down instead. 如果这不是您想要的,请指定要向上取整的环境,以及要向下取整的环境。

Note that this will round up to 3342, not 3342.00 - it doesn't preserve the original precision, because you've asked for an integer value by using Math.Ceiling . 请注意,这将舍入为3342,而不是3342.00-它不会保留原始精度,因为您已经使用Math.Ceiling要求提供整数值。

It's relatively unusual to then want to force the precision to 2, but you could divide by 100 and then multiply by 100 again, if necessary. 然后将精度强制为2是相对不寻常的,但是您可以除以100,然后在必要时再乘以100。 Alternatively, if you only need this for output you should look into formatting the result appropriately rather than changing the value. 或者,如果仅需要此输出 ,则应考虑对结果进行适当的格式化,而不是更改值。

Use Math.Round(number) if you want to round number to the nearest integer. 如果要将number四舍五入到最接近的整数,请使用Math.Round(number) Use Math.Round(number,digits) if you want to round number to a specified number of fractional digits. 使用Math.Round(number,digits) ,如果你想圆number到小数位指定数量。 If you want to round to lower/higer value use Math.Floor(number) / Math.Ceiling(number) instead. 如果要舍入到较低/较高的值,请改用Math.Floor(number) / Math.Ceiling(number)

To round monetary amounts to 5 cents: 四舍五入至5美分:

amount = 20 * int(amount / 20) 数量= 20 *整数(数量/ 20)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM