這篇文章將討論如何在 C# 中將浮點數舍入到小數點後兩位。
1.使用 ToString()
方法
我們可以使用 ToString()
將浮點值格式化為某些小數位的方法。這 ToString()
方法接受數字格式字符串並將當前實例值轉換為等效字符串。要將浮點數限制為 2 位小數,您可以使用 #.##
格式說明符,如下圖:
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("#.##"); Console.WriteLine(s); // 3.14 } } |
C# 提供了幾個標準格式說明符,可用於將浮點值舍入到兩位小數。這些在下面討論:
1. “0”自定義格式說明符.
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("0.00"); Console.WriteLine(s); // 3.14 } } |
2. 定點格式說明符 (F)
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("F2"); Console.WriteLine(s); // 3.14 } } |
3. 數字格式說明符 (N) 帶組分隔符
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { float f1 = 3.14285f; Console.WriteLine(f1.ToString("N2")); // 3.14 float f2 = 10000.874287f; Console.WriteLine(f2.ToString("N2")); // 10,000.87 } } |
2.使用 Decimal.Round()
方法
另一種常見的方法是使用 Decimal.Round()
將值四捨五入到指定小數位數的方法。使用此方法的優點是它保留值作為 Decimal
,而不是返回一個字符串。下面舉例說明。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { decimal d = 3.14285m; d = Decimal.Round(d, 2); Console.WriteLine(d); // 3.14 } } |
您還可以使用指定舍入十進制數的策略 MidpointRounding
枚舉。例如,以下代碼使用舍入約定 MidpointRounding.AwayFromZero
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { decimal d1 = 3.505m; d1 = Decimal.Round(d1, 2); Console.WriteLine(d1); // 3.50 decimal d2 = 3.505m; d2 = Decimal.Round(d2, 2, MidpointRounding.AwayFromZero); Console.WriteLine(d2); // 3.51 } } |
這 Math
類還提供 Round()
將值四捨五入到指定小數位數的方法。以下示例提供具有不同輸入的輸出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static void Main() { float f1 = 3.14285f; double d1 = Math.Round(f1, 2); Console.WriteLine(d1); // 3.14 float f2 = 3.1000f; double d2 = Math.Round(f2, 2); Console.WriteLine(d2); // 3.1 float f3 = 3.0000f; double d3 = Math.Round(f3, 2); Console.WriteLine(d3); // 3 } } |
3.使用 String.Format()
方法
類似於 ToString()
方法,您可以使用 String.Format()
將浮點值四捨五入到小數點後兩位的方法。以下示例說明了使用 #.##
格式說明符, 0
自定義格式說明符,定點格式說明符 (F)
, 和數字格式說明符 (N)
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = String.Format("{0:0.00}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:#.##}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:F2}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:N2}", f); Console.WriteLine(s); // 3.14 } } |
這就是 C# 中將浮點數四捨五入到小數點後 2 位的全部內容。