# 小数转整数 - c#除数取整

## 如何舍入到最接近的整数? (3)

``````double RoundToNearestEven(double value) =>
Math.Truncate(value) + Math.Truncate(value) % 2;``````

PS感谢@DmitryBychenko指出，铸造double to long并不是最明智的想法。

``````Math.Round(1122.5196d, 0, MidpointRounding.ToEven);       // result 1123
Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123``````

• `1122.51 --> 1122`
• `1122.9 --> 1122` （因为最近的int是`1123`但它是奇数`1122``1124` 更近
• `1123.0 --> 1124`下一个偶数值 ，下一个更高的偶数值）

``Math.Round(1122.5196d, 0, MidpointRounding.ToEven);``

``````   private int round_up_to_even(double number_to_round)
{
int converted_to_int = Convert.ToInt32(number_to_round);
if (converted_to_int %2 == 0) { return converted_to_int; }
double difference = (converted_to_int + 1) - number_to_round;
if (difference <= 0.5) { return converted_to_int + 1; }
return converted_to_int - 1;
}``````

``````using System;
class Example
{
public static void Main()
{
// Define a set of Decimal values.
decimal[] values = { 1.45m, 1.55m, 123.456789m, 123.456789m,
123.456789m, -123.456m,
new Decimal(1230000000, 0, 0, true, 7 ),
new Decimal(1230000000, 0, 0, true, 7 ),
-9999999999.9999999999m,
-9999999999.9999999999m };
// Define a set of integers to for decimals argument.
int[] decimals = { 1, 1, 4, 6, 8, 0, 3, 11, 9, 10};

Console.WriteLine("{0,26}{1,8}{2,26}",
"Argument", "Digits", "Result" );
Console.WriteLine("{0,26}{1,8}{2,26}",
"--------", "------", "------" );
for (int ctr = 0; ctr < values.Length; ctr++)
Console.WriteLine("{0,26}{1,8}{2,26}",
values[ctr], decimals[ctr],
Decimal.Round(values[ctr], decimals[ctr]));
}
}

// The example displays the following output:
//                   Argument  Digits                    Result
//                   --------  ------                    ------
//                       1.45       1                       1.4
//                       1.55       1                       1.6
//                 123.456789       4                  123.4568
//                 123.456789       6                123.456789
//                 123.456789       8                123.456789
//                   -123.456       0                      -123
//               -123.0000000       3                  -123.000
//               -123.0000000      11              -123.0000000
//     -9999999999.9999999999       9    -10000000000.000000000
//     -9999999999.9999999999      10    -9999999999.9999999999``````

“当舍入中点值时，舍入算法执行相等性测试。由于二进制表示和浮点格式的精度问题，该方法返回的值可能是意外的。”