本文主要介绍.NET(C#)通过Math.Round()方法,将小数只保留整数位变成最接近的偶数的方法。

实现的效果

1122.51 --> 1122
1122.9 --> 1122 (因为最近的整数是1123,但它是奇数,1122比1124更接近)
1123.0 --> 1124

1、通过Math.Round方法实现

double source = 1123.0;
// 1124.0
double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2;

测试代码

double[] tests = new double[] {
1.0,
1123.1,
1123.0,
1122.9,
1122.1,
1122.0,
1121.5,
1121.0,
};
string report = string.Join(Environment.NewLine, tests
.Select(item => $"{item,6:F1} -> {Math.Round(item / 2, MidpointRounding.AwayFromZero) * 2}"));
Console.Write(report);
输出结果:
1.0 -> 2
1123.1 -> 1124
1123.0 -> 1124
1122.9 -> 1122
1122.1 -> 1122
1122.0 -> 1122
1121.5 -> 1122
1121.0 -> 1122

2、通过类型转换和取余(%)来实现

using System;
using System.Linq;
public class Program
{
	public static void Main()
	{
		double[] tests = new double[] {
			1.0,
    		1123.1,
    		1123.0,
    		1122.9,
    		1122.1,
    		1122.0,
    		1121.5,
  		};
		foreach (var item in tests)
		{
			Console.WriteLine(item + " -> " + RoundToNearestEven(item));
                      //Console.WriteLine(item + " -> " + round_up_to_even(item));
		}
	}
    private static long RoundToNearestEven(double value)
	{
		return (long)value + (long)value % 2;
	}
       private static 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;
        }
}