どうも、ちょげ(@chogetarou)です。
数値を銀行丸めで四捨五入する方法を紹介します。
方法

数値を銀行丸めで四捨五入するには、Math.Round()を使います。
まず、Math.Round()を呼び出します。
Math.Round()の第1引数に数値、第2引数にMidpointRounding.ToEvenを指定します。
Math.Round(number, MidpointRounding.ToEven);
上記のMath.Round()は、第1引数の数値の小数点以下を銀行丸めで四捨五入した数値を返します。
また、Math.Round()で桁数を指定する場合は、第3引数にMidpointRounding.ToEvenを指定します。
Math.Round(number, digits, MidpointRounding.ToEven);
使用例
using System;
public class Example
{
public static void Main()
{
double num1 = Math.Round(2.5, MidpointRounding.ToEven);
double num2 = Math.Round(1.455, 2, MidpointRounding.ToEven);
double num3 = Math.Round(25.65, 1, MidpointRounding.ToEven);
Console.WriteLine(num1); //2
Console.WriteLine(num2); //1.46
Console.WriteLine(num3); //25.6
}
}
コメント