如何在表达式中使用String.Format说明符?

时间:2014-05-18 02:51:50

标签: c# string.format

double paintneeded = area/450;

当我运行上述内容时,我将输出设为0.444444444,但我只想0.44

我尝试了这个,但它引发了一个错误:

double paintneeded = String.Format("{0:0.00}", (area/450));

Console.WriteLine("Number of Gallons paint needed:\t{0}", paintneeded);

如何在此表达式中使用String.Format?或者我可以在Console.WriteLine中使用它吗?如果是这样,我该如何实现呢?

2 个答案:

答案 0 :(得分:2)

Console.WriteLine("Number of Gallons paint needed:\t{0:F2}", area/450.0);

答案 1 :(得分:0)

首先,转换为字符串:

double area = 150;
string paintneeded = string.Format("{0:0.00}", (area/450d)).ToString();

Console.WriteLine("Number of Gallons paint needed:\t{0}", paintneeded); 

第二种方式,转换为double:

double area = 150;
double paintneeded = area/450d;

Console.WriteLine("Number of Gallons paint needed:\t{0:0.00}", paintneeded);