这篇文章将讨论如何在 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 位的全部内容。