Right padding with zeros in Java

Caina Santos picture Caina Santos · Oct 18, 2012 · Viewed 43.3k times · Source

Sorry if this question was made already, I've made a deep search and nothing.

Now, I know that:

String.format("%05d", price);

Will be padding my price with zeros to the left, so a price of 25 will result in 00025

What if I want to pad them to the right, so the result is 25000? How do I do that using only String.format patterns?

Answer

Reimeus picture Reimeus · Oct 18, 2012

You could use:

String.format("%-5s", price ).replace(' ', '0')

Can I do this using only the format pattern?

String.format uses Formatter.justify just like the String.printf method. From this post you will see that the output space is hard-coded, so using the String.replace is necessary.