Ampati Hareesh
Ampati Hareesh

Reputation: 1872

Which format to print the number with leading spaces?

Input:

3
100
12 

Output:

      003
      100
      012

I need to print the numbers after 10 spaces and then print the number using format specifier all starting from 11th position as shown. I tried %013d format specifier, but the output contains trailing zeroes, but I need spaces.

Upvotes: 3

Views: 2935

Answers (2)

vefthym
vefthym

Reputation: 7462

if you store your number as an int x, then just use:

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

If you have a String text = "test"; that you wish to include in the first 10 chars before the number (assuming that its length is less than 10), then you can do the following:

System.out.format("%10s%03d", text, x);

This will print:

      test003

If you want text to appear on the beginning of the string, then use:

System.out.format("%-10s%03d", text, x);

This will print:

test      003

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100219

You can use the formatting twice like this:

System.out.format("%13s", String.format("%03d", x));

So first you format the number to 0-padded string, then format this string to space-padded string.

Upvotes: 1

Related Questions