どうも、ちょげ(@chogetarou)です。
Math.Round()を使って、doubleの小数を四捨五入してintの整数に変換する方法を紹介します。
方法

Math.Round()でdoubleの小数を四捨五入してintの整数に変換するには、(int)を使います。
まず、先頭に(int)を付けたMath.Round()を呼び出します。
そして、Math.Round()の引数にdouble型の値を指定します。
(int)Math.Round(doubleValue);
上記のMath.Round()は、引数に指定したdoubleを四捨五入したintの数値を返します。
使用例
using System;
public class Example
{
public static void Main()
{
int num1 = (int)Math.Round(2.71);
int num2 = (int)Math.Round(1.455);
int num3 = (int)Math.Round(26.5);
Console.WriteLine(num1); //3
Console.WriteLine(num2); //1
Console.WriteLine(num3); //27
}
}
コメント