Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java System.out.print formatting

Tags:

java

format

Here is my code (well, some of it). The question I have is, can I get the first 9 numbers to show with a leading 00 and numbers 10 - 99 with a leading 0.

I have to show all of the 360 monthly payments, but if I don't have all month numbers at the same length, then I end up with an output file that keeps moving to the right and offsetting the look of the output.

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();

Results:

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  

What I want to see is:

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  

What other code do you need to see from my class that could help?

like image 454
RazorSharp Avatar asked Mar 24 '12 07:03

RazorSharp


3 Answers

Since you're using formatters for the rest of it, just use DecimalFormat:

import java.text.DecimalFormat;

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

Alternative you could do whole job in whole line using 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));
like image 184
Adam Avatar answered Oct 05 '22 23:10

Adam


Since you are using Java, printf is available from version 1.5

You may use it like this

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

For Example:

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

Will Give You

005 055 555

as output

See: System.out.printf and Format String Syntax

like image 45
Jomoos Avatar answered Oct 05 '22 23:10

Jomoos


Use System.out.format

like image 41
Hari Menon Avatar answered Oct 05 '22 22:10

Hari Menon