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?
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.
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.
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.
To display numbers with leading zeros in Java, useDecimalFormat("000000000000").
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.
Try this :
String RightPaddedString = org.apache.commons.lang.StringUtils.rightPad(InputString,NewStringlength,'paddingChar');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With