在Java中的双精度列表中对齐小数

时间:2012-07-13 01:46:55

标签: java alignment double decimal

以下是代码部分:

    System.out.println("The values of pi from term " + (userNum - 9) + " to term " + userNum + " are:");        
        for (int x = 1; x < userNum; x++) 
            {
                if (x % 2 == 1)
                    sum = sum + (4.0/(2 * x - 1));
                else
                    sum = sum - (4.0/(2 * x - 1));
            System.out.println("Term " + (x) + ": " + sum);
            }

这是输出:

The values of pi from term 2 to term 11 are:
Term 1: 4.0
Term 2: 2.666666666666667
Term 3: 3.466666666666667
Term 4: 2.8952380952380956
Term 5: 3.3396825396825403
Term 6: 2.9760461760461765
Term 7: 3.2837384837384844
Term 8: 3.017071817071818
Term 9: 3.2523659347188767
Term 10: 3.0418396189294032

第10项的小数需要与其他小数对齐。怎么能在Java中完成?感谢。

3 个答案:

答案 0 :(得分:3)

System.out.printf类似于(但不是)C printf方法。您可以使用它来执行以下操作:

int spaces = (int)Math.log10(Math.abs(userNum)) + 1;
String myFormat = "Term %" + spaces +"d: %.10f\n";

//inside the for loop
System.out.printf(myFormat , x, sum);

编辑:您可以使用%2d来使用2个空格的数字,如果数字更大则会使用更多的空格。

更多信息:

答案 1 :(得分:1)

如果您使用Apache commons lang,则可以使用StringUtils课程来完成您的需要:

System.out.println("Term " + 
    StringUtils.leftPad("" + x, (userNum.length() - x.length()), ' ')
      + ": " + sum);

答案 2 :(得分:0)

似乎您想在Term之后添加空格,具体取决于x的位数:

    int j = String.valueOf(x).length();
    String sp = "";
    while( j++ < String.valueOf(userNum).length() )
        sp += " ";
    System.out.printf("Term %s %d : %.15f\n", sp, x, sum);