Java System.out.print格式化

时间:2012-03-24 07:00:57

标签: java format

这是我的代码(好吧,其中一些)。我的问题是,我可以将前9个数字显示为前导00,数字10 - 99显示前导0。

我必须显示所有360个月的付款,但如果我没有相同长度的所有月份数字,那么我最终会得到一个输出文件,该文件一直向右移动并抵消了输出。

System.out.print((x + 1) + "  ");  // the payment number
System.out.print(formatter.format(monthlyInterest) + "   ");    // round our interest rate
System.out.print(formatter.format(principleAmt) + "     ");
System.out.print(formatter.format(remainderAmt) + "     ");
System.out.println();

结果:

8              $951.23               $215.92         $198,301.22                         
9              $950.19               $216.95         $198,084.26                         
10              $949.15               $217.99         $197,866.27                         
11              $948.11               $219.04         $197,647.23  

我想看到的是:

008              $951.23               $215.92         $198,301.22                         
009              $950.19               $216.95         $198,084.26                         
010              $949.15               $217.99         $197,866.27                         
011              $948.11               $219.04         $197,647.23  

您需要从我的课程中看到哪些其他代码可以提供帮助?

6 个答案:

答案 0 :(得分:9)

由于您正在使用格式化程序,只需使用DecimalFormat:

import java.text.DecimalFormat;

DecimalFormat xFormat = new DecimalFormat("000")
System.out.print(xFormat.format(x + 1) + " ");

替代方案,您可以使用printf在整行中完成整个工作:

System.out.printf("%03d %s  %s    %s    \n",  x + 1, // the payment number
formatter.format(monthlyInterest),  // round our interest rate
formatter.format(principleAmt),
formatter.format(remainderAmt));

答案 1 :(得分:5)

由于您使用的是Java,因此版本1.5中提供了printf

您可以像这样使用它

System.out.printf("%03d ", x);

例如:

System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);

会给你

005 055 555

作为输出

请参阅:System.out.printfFormat String Syntax

答案 2 :(得分:4)

答案 3 :(得分:3)

有点喜欢这个

public void testPrintOut() {
    int val1 = 8;
    String val2 = "$951.23";
    String val3 = "$215.92";
    String val4 = "$198,301.22";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

    val1 = 9;
    val2 = "$950.19";
    val3 = "$216.95";
    val4 = "$198,084.26";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}

答案 4 :(得分:0)

你确定你想要“055”而不是“55”吗?有些程序将前导零解释为八进制,因此它将055读为(十进制)45而不是(十进制)55。

这应该只是意味着删除'0'(零填充)标志。

例如,将System.out.printf("%03d ", x);更改为更简单的System.out.printf("%3d ", x);

答案 5 :(得分:0)

只需使用\t来隔开它。

示例:

System.out.println(monthlyInterest + "\t")

//as far as the two 0 in front of it just use a if else statement. ex: 
x = x+1;
if (x < 10){
    System.out.println("00" +x);
}
else if( x < 100){
    System.out.println("0" +x);
}
else{
    System.out.println(x);
}

还有其他方法可以做到,但这是最简单的。