我想打印一个double作为字符串,它总是显示2个小数位,即使它们是“00”。
预期产量为30.00 但实际结果是30。
class Program
{
static void Main(string[] args)
{
short a = 10;
int b = 20;
double d = (double)(a + b);
Console.WriteLine(d);
Console.ReadKey();
}
}
答案 0 :(得分:2)
<强>更新强>
由于问题不是“转换”从int / short到double,而是生成字符串的格式,在打印时我更新了答案。
无需将Int / Short明确地转换/转换为Double。这是暗示完成的。
Implicit Cast的工作方式如下所示:
int i = 3;
double d = i;
代码的工作示例: 没有必要进行明确的演员表。
class Program
{
static void Main(string[] args)
{
short a = 10;
int b = 20;
double d = a + b;
Console.WriteLine( d.ToString("0.00"));
Console.ReadKey();
}
}
结果:
或者您可以使用Convert.ToDouble() 用法示例:
int i = 3;
double x = Convert.ToDouble(i);
感谢Rand Random提供以下提示。
您也可以使用d.ToString("N2")
,这样就可以获得千位分隔符。
有关“0.00”和“N2”差异的更多信息,请查看this帖子。
答案 1 :(得分:0)
只需更改此行
Console.WriteLine(d);
到此
Console.WriteLine( d.ToString("0.00"));
这应该有效,输出为30.00。 它使用给定格式提供程序的formatting the string。