简体   繁体   English

C#-十进制转换为整数并根据值取整

[英]C# - Decimal to integer and round depending on value

I'm trying convert a decimal into integer and want to round the value up or down depending on the situation. 我正在尝试将decimal转换为integer并希望根据情况将值四舍五入。

Basically example is: 基本上的例子是:

  • 12/3 = 4 so should round to 4 12/3 = 4,因此应四舍五入
  • 11/3 = 3.66666 so should round to 4 11/3 = 3.66666,因此应四舍五入
  • 10/3 = 3 = 3.33333 so should round to 3 10/3 = 3 = 3.33333,因此应四舍五入
  • 9/3 = 3 so should round to 3 9/3 = 3,因此应四舍五入到3

Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers. 无论我在互联网上发现的内容总是四舍五入,或者总是四舍五入,从不根据数字做出判断。

If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero) . 如果x是您要四舍五入的数字,并且您需要“正常”的四舍五入行为(因此,.5总是四舍五入),则需要使用Math.Round(x, MidpointRounding.AwayFromZero) Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int , you need to cast the result of Round() : 请注意,如果您实际上是在计算分数,并且分子和分母是整数,则需要将其中一个强制转换为首先翻倍(否则,除法运算符将产生一个四舍五入的整数),并且如果希望将结果舍入作为一个int ,您需要转换Round()的结果:

int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);

Does Math.Round(d) do what you require? Math.Round(d)是否满足您的要求?

Return Value: The integer nearest parameter d. 返回值:最接近的整数d。 If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. 如果d的小数部分在两个整数之间,其中一个是偶数,另一个是奇数,则返回偶数。 Note that this method returns a Decimal instead of an integral type. 请注意,此方法返回的是Decimal而不是整数类型。

Check out the Round reference page 查看回合参考页

Math.Round(value) should do what you want. Math.Round(value)应该做你想要的。 Examples console app code to demonstrate: 控制台应用程序代码示例演示:

Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();

Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();

Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();

Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();

Console.ReadKey();

You could try this 你可以试试这个

Math.Round(d, 0, MidpointRounding.AwayFromZero)

Sometime, people add 0.5 to the number before converting to int. 有时,人们在转换为int之前将数字加0.5。

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

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