Formatting Java System.out.print

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

I need to show all 360 monthly payments, but if I don’t have all the month numbers on the same length, I get an output file that moves to the right and compensates for the appearance 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:

 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 should I see from my class that might help?

+4
source share
6 answers

Since you are using formatters for the rest, just use DecimalFormat:

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

Alternatively, you can do the whole job in a 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)); 
+9
source

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

You can use it like this:

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

Example:

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

Gives you

005 055 555

as a conclusion

See: System.out.printf and String Syntax Format

+5
source
+4
source

Something like it

 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)); } 
+3
source

Are you sure you want "055" and not "55"? Some programs interpret the leading zero as octal, so it will read 055 as (decimal) 45 instead of (decimal) 55.

This should only mean resetting the flag "0" (zero fill).

for example, modify System.out.printf("%03d ", x); to a simpler System.out.printf("%3d ", x);

0
source

Just use \t to scroll it.

Example:

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

There are other ways to do this, but this is the easiest.

0
source

Source: https://habr.com/ru/post/1403202/


All Articles