Mathクラスには整数を任意の桁数で四捨五入する、例えば5を10に、49を50に四捨五入するとメソッドは用意されていません。 このような目的には、Math.Roundを使って次のようなコードを実装する必要があります。
Math.Roundメソッドを使って整数を任意の桁数で四捨五入をする
Imports System
Class Sample
' 整数nのd桁目を四捨五入する
Shared Function RoundInt(ByVal n As Integer, ByVal d As Integer) As Integer
' 一旦10^dの逆数で数を小数化してMath.Roundで四捨五入したのち、10^dの倍数で元に戻す
Dim s As Double = Math.Pow(10.0, d)
Return CInt(Math.Round(n / s, 0, MidpointRounding.AwayFromZero) * s)
End Function
Shared Sub 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()
End Sub
End Class
実行結果
0 10 20 20 0 100 100 0 1000