Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right padding with zeros in Java

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?

like image 617
Caina Santos Avatar asked Oct 18 '12 19:10

Caina Santos


People also ask

How do I right a string pad in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How can I pad a string with zeros on the left?

To pad zeros to a string, use the str. zfill() method. It takes one argument: the final length of the string you want and pads the string with zeros to the left.

How do I add 0 to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.

How do you keep leading zeros in Java?

To display numbers with leading zeros in Java, useDecimalFormat("000000000000").


2 Answers

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.

like image 133
Reimeus Avatar answered Sep 30 '22 23:09

Reimeus


Try this :

String RightPaddedString = org.apache.commons.lang.StringUtils.rightPad(InputString,NewStringlength,'paddingChar'); 
like image 37
Prasad D Avatar answered Sep 30 '22 22:09

Prasad D