Mathクラスには整数を任意の桁数で四捨五入する、例えば5を10に、49を50に四捨五入するとメソッドは用意されていません。 このような目的には、Math.Roundを使って次のようなコードを実装する必要があります。
Math.Roundメソッドを使って整数を任意の桁数で四捨五入をする
using System;
class Sample {
// 整数nのd桁目を四捨五入する
static int RoundInt(int n, int d)
{
// 一旦10^dの逆数で数を小数化してMath.Roundで四捨五入したのち、10^dの倍数で元に戻す
var s = Math.Pow(10.0, d);
return (int)(Math.Round(n / s, 0, MidpointRounding.AwayFromZero) * s);
}
static void Main()
{
// 整数1桁目を四捨五入
Console.WriteLine(RoundInt(4, 1));
Console.WriteLine(RoundInt(5, 1));
Console.WriteLine(RoundInt(15, 1));
Console.WriteLine(RoundInt(24, 1));
Console.WriteLine();
// 整数2桁目を四捨五入
Console.WriteLine(RoundInt(49, 2));
Console.WriteLine(RoundInt(50, 2));
Console.WriteLine(RoundInt(149, 2));
Console.WriteLine();
// 整数3桁目を四捨五入
Console.WriteLine(RoundInt(499, 3));
Console.WriteLine(RoundInt(500, 3));
Console.WriteLine();
}
}
実行結果
0 10 20 20 0 100 100 0 1000