Format()数字字符串,用逗号转换为for循环中的字符串

时间:2016-08-10 18:10:29

标签: c# for-loop string-formatting

我已经知道如何使用逗号格式化数字字符串,就像我需要this thread一样,事实上,我正在尝试将接受的答案应用于我的案例。

然而,从我看到的,它处理预定的字符串变量。在我的例子中,它正在运行for循环,它将double值转换为string并将输出显示为表行。

for (double i = 1; i <= years; i++)
{
                              //number of years         //future value
   richTextBoxResults.Text += i.ToString().PadLeft(3) + (presentValue * Math.Pow(((interestRate / 100 / periods) + 1), (periods * i))).ToString("$#.00").PadLeft(28) + "\n";
}

为了简单起见,3个输出行应足以获得想法

Years                                Future Value
__________________________________________________
  1                                    $1234567.89
  2                                    $2345678.90
  3                                    $3456789.01

我尝试在.ToString(“$#。00”)方法之后在循环中使用Format(),但是,我收到了Method() cannot be accessed _ with an instance reference的错误。但是,我不确定如何将这些答案应用到我的案例中。

我正在考虑创建一个字符串变量,它会临时存储值并对其进行格式化。但我想知道是否有更优雅的解决方案。

我仍然可以应用Format()方法(可能在不同的角度下),所以我的输出将如下所示

Years                                Future Value
__________________________________________________
  1                                  $1,234,567.89
  2                                  $2,345,678.90
  3                                  $3,456,789.01

或者我需要改变我的做法?

3 个答案:

答案 0 :(得分:3)

您的代码不可读,这使您难以理解问题。您在)之前还有.ToString

Math.Pow(((interestRate / 100 / periods) + 1), (periods * i)).ToString("$#.00").PadLeft(28)

您可以使用"$0,#.00"来应用千位分隔符。

答案 1 :(得分:1)

要使代码可读,请将数据放入变量中。然后像这样格式化。

 var _value = presentValue * Math.Pow(((interestRate / 100 / periods) + 1), (periods * i));
 richTextBoxResults.Text+= i.ToString().PadLeft(3) + String.Format("{0:0.00}",_value) .PadLeft(28) ;

答案 2 :(得分:0)

您必须将Format()称为string类的静态方法:

string.Format(/*YourParameters*/)