简体   繁体   中英

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?

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.

试试这个 :

String RightPaddedString = org.apache.commons.lang.StringUtils.rightPad(InputString,NewStringlength,'paddingChar');

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);
}

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@

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');

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

如果您想不使用格式或任何功能,请使用这个简单的技巧System.out.println(price+"000");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM