HOWTO · Csharp
在 C# 中把浮點數轉換為 Int
在 C# 中,有 4 種主要方法可用於將浮點數轉換為 int,顯式型別轉換方法,Math.Ceiling()函式,Math.Floor()函式和 Math.Round()函式。
本頁內容
在 C# 中將 float 轉換為 int 時,請依照你希望如何處理小數部分來選擇操作:直接轉型會朝零截斷,Math.Ceiling() 會朝正無限方向進位,Math.Floor() 會朝負無限方向捨入,而 Math.Round() 則會選擇最接近的整數。每種轉換的結果都是 int,因此輸入的小數值可能會改變。
在 C# 中使用明確型別轉換將浮點數轉為整數
如果你想直接捨去小數部分,直接轉型是最簡單的做法。它會朝零截斷,因此正數和負數都會朝零移動,而不是朝負無限方向移動。以下完整程式會轉換正數與負數:
using System;
class Program
{
static void Main()
{
float positive = 10.9f;
float negative = -10.9f;
int positiveResult = (int)positive;
int negativeResult = (int)negative;
Console.WriteLine(positiveResult);
Console.WriteLine(negativeResult);
}
}
轉型會移除小數部分,同時保留朝零移動的方向:例如,10.9f 會變成 10,而 -10.9f 會變成 -10。結果變數的型別是 int。此範例以程式碼提供,且在本次撰寫階段尚未執行。
在 C# 中使用 Math.Ceiling() 函式將浮點數轉為整數
當你希望數值朝正無限方向捨入時,請使用 Math.Ceiling()。它會傳回 double,因此呼叫此方法後,還要將結果轉型為 int。對負數而言,朝正無限方向捨入會使數值更接近零:
using System;
class Program
{
static void Main()
{
float positive = 10.2f;
float negative = -10.2f;
int positiveResult = (int)Math.Ceiling(positive);
int negativeResult = (int)Math.Ceiling(negative);
Console.WriteLine(positiveResult);
Console.WriteLine(negativeResult);
}
}
在此,Math.Ceiling() 會先將每個數值沿數線向上捨入,再由轉型將結果整數存為 int。例如,正數輸入會變成 11,負數輸入則會變成 -10。此範例在本次撰寫階段尚未執行。
在 C# 中使用 Math.Floor() 函式將浮點數轉為整數
當你希望數值朝負無限方向捨入時,請使用 Math.Floor()。和 Math.Ceiling() 一樣,它會傳回 double;若要儲存整數,請將其結果轉型為 int:
using System;
class Program
{
static void Main()
{
float positive = 10.2f;
float negative = -10.2f;
int positiveResult = (int)Math.Floor(positive);
int negativeResult = (int)Math.Floor(negative);
Console.WriteLine(positiveResult);
Console.WriteLine(negativeResult);
}
}
朝負無限方向捨入後,正數輸入會得到 10,負數輸入則會得到 -11。這與直接轉型不同:對負的小數而言,直接轉型會朝零移動。兩個結果變數的型別都是 int。此範例在本次撰寫階段尚未執行。
在 C# 中使用 Math.Round() 函式將浮點數轉為整數
如果你需要最接近的整數,請使用 Math.Round()。它會傳回 double,因此可以將結果轉型為 int。以下輸入都不是正好位於兩個整數中間的值,因此此範例不涉及中點捨入規則:
using System;
class Program
{
static void Main()
{
float positive = 10.8f;
float negative = -10.8f;
int positiveResult = (int)Math.Round(positive);
int negativeResult = (int)Math.Round(negative);
Console.WriteLine(positiveResult);
Console.WriteLine(negativeResult);
}
}
兩個最接近的整數依序為 11 和 -11。轉換時,小數值確實會改變;當你的需求是捨入至最接近的值時,Math.Round() 就很適用,但它並非在所有情況下都優於其他轉換方式。結果都是 int 值。此範例在本次撰寫階段尚未執行。