在.NET 4 Math.Round()行为 [英] Math.Round() behaviour in .NET 4

查看:195
本文介绍了在.NET 4 Math.Round()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能显示的文件:
  <一href="http://stackoverflow.com/questions/977796/in-c-math-round2-5-result-is-2-instead-of-3-are-you-kidding-me">In C#:Math.Round(2.5)结果是2(而不是3)!你在开玩笑吧?
  净回合错误

我有一个中间值(number.5),我需要指定如何将被舍(上限或下限值。)

我理解 Math.Round MidPointRounding 参数的行为,但是这并没有解决我的问题:

  //连
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6

// AwayFromZero
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6

//在一种情况下,我需要
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 5

//我需要另一种情况
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
 

解决方案

您有过载 Math.Round 是采取从 A枚举值MidpointRounding

这有两个选项:

  • ToEven(默认)也被称为银行家四舍五入。将舍入到最接近一对。因此,2.5变为2,而3.5变成4。
  • AwayFromZero:始终轮X.5高达X + 1;因此,2.5例如变成3。

Possible Duplicates:
In C#: Math.Round(2.5) result is 2 (instead of 3)! Are you kidding me?
.Net Round Bug

I have a halfway value (number.5) and I need to specify how this will be rounded (upper or lower value.)

I understand the behaviour of Math.Round with the MidPointRounding parameter but that does not solve my problem:

// To Even
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6

// AwayFromZero
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6

// in one case I need 
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 5

// another case I need
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6

解决方案

You have a overload to Math.Round that take a enum value from MidpointRounding.

This has two options:

  • ToEven (default) Also called bankers rounding. Will round to the nearest pair. So 2.5 becomes 2, while 3.5 becomes 4.
  • AwayFromZero: Always round X.5 up to X+1; So 2.5 for example becomes 3.

这篇关于在.NET 4 Math.Round()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆