我是 C# 的新手,使用过 Java。
我希望输出 4.5 - 2.7 的表达式......在 Java 中,我会简单地编写 System.out.format("%.2f\n", 4.5 - 2.7);
在 C# 中,我使用了 Console.WriteLine(4.5 - 2.7);但我想打印 2 个小数位。
有人能解释一下我是如何实现这一目标的吗?
最佳答案
使用 String.Format
(Link To Documentation)
使用格式 {Parameter Number:Decimal Places}
Console.WriteLine(String.Format(" We are going to format 15.6345 as {0:0.00}",15.6345));
测试一下 here! .祝你好运!
编辑/澄清
来自
Parameter Number
, String.Format 将字符串的第一个输入之后的所有其他输入作为要格式化并放入字符串的值。每次 {x:yyz} 出现在字符串中时,System.String.Format 将格式化
x
风格yyz
,其中 x
是传入值的索引。在我上面的例子中,
15.6345
是 x
, 和格式 0.00
是 yyz
.您可以通过以下方式格式化 2 个数字或重复一个数字:
Console.WriteLine(String.Format(" We are going to format 15.6345 as {0:0.00} , the format 3.123 as 3.1 {1:0.0} , then repeat 15.6345 as 15.6 {0:0.0}",15.6345,3.123));
关于Java 到 C# 格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68795938/