Java System.out.print格式化

Raz*_*arp 4 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();
Run Code Online (Sandbox Code Playgroud)

结果:

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  
Run Code Online (Sandbox Code Playgroud)

我想看到的是:

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  
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*dam 9

由于您在其余部分使用格式化程序,因此只需使用DecimalFormat:

import java.text.DecimalFormat;

DecimalFormat xFormat = new DecimalFormat("000")
System.out.print(xFormat.format(x + 1) + " ");
Run Code Online (Sandbox Code Playgroud)

替代方案,您可以使用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));
Run Code Online (Sandbox Code Playgroud)


Jom*_*oos 5

由于您使用的是Java,printf因此可以从1.5版开始使用

你可以像这样使用它

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

例如:

System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);
Run Code Online (Sandbox Code Playgroud)

会给你

005 055 555

作为输出

请参阅:System.out.printf格式字符串语法