27

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?

Samet ÖZTOPRAK
  • 2,428
  • 3
  • 23
  • 26
Caina Santos
  • 769
  • 1
  • 7
  • 14

7 Answers7

48

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.

Community
  • 1
  • 1
Reimeus
  • 152,723
  • 12
  • 195
  • 261
8

Try this :

String RightPaddedString = org.apache.commons.lang.StringUtils.rightPad(InputString,NewStringlength,'paddingChar');
Prasad D
  • 1,418
  • 1
  • 14
  • 7
3

Please try to read this doc, look if the library of apache commons StringUtils can help you

I've made a code like this :

import org.apache.commons.lang3.StringUtils;

public static void main(String[] args)  {   
  String str = "123";
  str = StringUtils.leftPad(str,10,"0"); //you can also look the rightPad function.
  System.out.println(str);
}
1

Credits to beginnersbook.com, this is a working solution for the problem:

public class PadRightTest {
  public static void main(String[] argv) {
    System.out.println("#" + rightPadZeros("mystring", 10) + "@");
    System.out.println("#" + rightPadZeros("mystring", 15) + "@");
    System.out.println("#" + rightPadZeros("mystring", 20) + "@");
  }

  public static String rightPadZeros(String str, int num) {
    return String.format("%1$-" + num + "s", str).replace(' ', '0');
  }
}

and the output is:

#mystring00@
#mystring0000000@
#mystring000000000000@
madx
  • 5,688
  • 4
  • 47
  • 53
1

In my case I solved this using only native Java.

StringBuilder sb = new StringBuilder("1234");
sb.setLength(9);
String test = sb.toString().replaceAll("[^0-9]", "0");
System.out.println(test);

So it printed out : 123400000

0

if you want to do without format or any function then used this simple trick System.out.println(price+"000");

Team Work
  • 35
  • 1
  • 7
  • The OP has requested that it needs to be done using String.format pattern. This approach though solves the requirement but is not flexible. What is instead of 25000 the developer wants 2500 or 250000. – Soumya Aug 25 '17 at 16:25
0

Use this function for right padding.

private String rightPadding(String word, int length, char ch) {
   return (length > word.length()) ? rightPadding(word + ch, length, ch) : word;
}

how to use?

rightPadding("25", 5, '0');
Samet ÖZTOPRAK
  • 2,428
  • 3
  • 23
  • 26