C# 保留两位小数的几种方法
有多种方法可以在 C# 中保留两位小数,以下是其中的一些方法:
- 使用 ToString() 方法
double number = 3.1415926;
string result = number.ToString('0.00');
Console.WriteLine(result); // 输出 '3.14'
- 使用 String.Format() 方法
double number = 3.1415926;
string result = String.Format('{0:0.00}', number);
Console.WriteLine(result); // 输出 '3.14'
- 使用 $ 字符串插值
double number = 3.1415926;
string result = $'{number:0.00}';
Console.WriteLine(result); // 输出 '3.14'
无论使用哪种方法,都需要将数字转换为字符串,并使用格式化字符串指定保留两位小数。格式化字符串的语法如下:
{index[,alignment][:formatString]}
其中,index 是要格式化的参数的位置,从 0 开始计数;alignment 是可选的,表示输出的宽度;formatString 是格式化字符串,用于指定输出格式。在上述示例中,我们使用了格式化字符串 '0.00' 来指定保留两位小数。
原文地址: https://www.cveoy.top/t/topic/nVzk 著作权归作者所有。请勿转载和采集!