在 C# 中將雙精度數轉換為整數
- 在 C# 中使用顯式型別轉換將雙精度值轉換為整型
- 
          
            使用 C# 中的 Convert.ToInt32()函式將 Double 轉換為 Int
- 
          
            使用 C# 中的 Math.Round()函式將 Double 轉換為 Int
 
本教程將介紹在 C# 中將雙精度值轉換為 int 值的方法。
在 C# 中使用顯式型別轉換將雙精度值轉換為整型
眾所周知,雙精度資料型別比整數需要更多的位元組。我們需要使用顯式型別轉換在 C# 中把一個雙精度值轉換為一個 int 值。下面的程式碼示例向我們展示瞭如何在 C# 中使用顯式型別轉換將 double 值轉換為 int 值。
using System;
namespace convert_double_to_int {
  class Program {
    static void Main(string[] args) {
      double d = 7.7;
      int x = (int)d;
      Console.WriteLine(x);
    }
  }
}
輸出:
7
我們使用 C# 中的顯式型別轉換將雙精度值 d 轉換為整數值 x。我們得到 7 作為輸出,因為顯式型別轉換完全忽略了小數點後的值。不建議使用顯式型別轉換,因為在使用顯式型別轉換時會發生大量資料丟失。
使用 C# 中的 Convert.ToInt32() 函式將 Double 轉換為 Int
Convert.ToInt32() 函式將值轉換為整數值。Convert.ToInt32() 函式將值轉換為等效的 32 位帶符號整數。下面的程式碼示例向我們展示瞭如何使用 Convert.ToInt32() 函式在 C# 中將雙精度值轉換為整數值。
using System;
namespace convert_double_to_int {
  class Program {
    static void Main(string[] args) {
      double d = 7.7;
      int x = Convert.ToInt32(d);
      Console.WriteLine(x);
    }
  }
}
輸出:
8
在上面的程式碼中,我們使用 C# 中的 Convert.ToInt32() 函式將雙精度值 d 轉換為整數值 x。
使用 C# 中的 Math.Round() 函式將 Double 轉換為 Int
Math.Round() 函式用於將十進位制值舍入為其最接近的整數值。Math.Round() 返回一個十進位制值,四捨五入到最接近的整數值。以下程式碼示例向我們展示瞭如何使用 Math.Round() 函式在 C# 中將十進位制值轉換為整數值。
using System;
namespace convert_double_to_int {
  class Program {
    static void Main(string[] args) {
      double d = 7.7;
      int x = (int)Math.Round(d);
      Console.WriteLine(x);
    }
  }
}
輸出:
8
在上面的程式碼中,我們使用 C# 中的 Math.Round() 函式將雙精度值 d 轉換為整數值 x。為了將值儲存在整數變數 x 中,我們必須使用顯式型別轉換,因為 Math.Round() 函式返回一個雙精度值。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn