简体   繁体   English

C#Math.Round(值/ 2)。 值是十进制。 功能不适用于一个特定的数字4.5

[英]C# Math.Round(value / 2). value is decimal. function not working for one specific number 4.5

I am looking to round decimal, 0.1 to 0.4 round down and 0.5 to 0.9 round up tried these but for some reason if value is 4.5 it rounds to 4 and not 5 all other values work fine. 我想四舍五入小数,向下舍入到0.1到0.4,向上舍入到0.5到0.9,但是由于某些原因,如果值是4.5,则四舍五入到4而不是5,所有其他值都可以正常工作。 3.5=4.0 , 5.5=6.0 but 4.5 =4.0 expecting 5.0 3.5 = 4.0,5.5 = 6.0但4.5 = 4.0期望5.0

Math.Round(value / 2)
Math.Round(Math.Round(value / 2),0, MidpointRounding.AwayFromZero)

Your first line is using the default type of rounding (known as banker's rounding). 您的第一行使用默认的舍入类型(称为银行家的舍入)。 Your second line almost gets what you want, but you don't need to include two calls to Math.Round() . 您的第二行几乎可以得到您想要的,但是您不需要包括对Math.Round()两次调用。

For what you're wanting, it should probably look like this: 对于您想要的东西,它可能看起来应该像这样:

Math.Round((value / 2), 0, MidpointRounding.AwayFromZero)
// e.g. 3.5 => 4, 4.5 => 5, 5.5 => 6, etc.

Read more about banker's rounding here , and read more about Math.Round() here . 了解更多关于银行家的舍入这里 ,并了解更多关于Math.Round() 在这里

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

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