温馨提示×

C#双精度数保留小数的方法

c#
小樊
89
2024-08-08 20:41:36
栏目: 编程语言

要在C#中保留双精度数的小数位数,可以使用以下方法:

  1. 使用ToString方法
double num = 10.56789;
string result = num.ToString("0.00"); // 保留两位小数
Console.WriteLine(result); // 输出:10.57
  1. 使用String.Format方法
double num = 10.56789;
string result = String.Format("{0:0.00}", num); // 保留两位小数
Console.WriteLine(result); // 输出:10.57
  1. 使用Math.Round方法
double num = 10.56789;
double result = Math.Round(num, 2); // 保留两位小数
Console.WriteLine(result); // 输出:10.57

以上是三种常用的方法来保留双精度数的小数位数。您可以根据自己的需要选择合适的方法。

0