Right padding with zeros in Java

心已入冬 提交于 2019-11-26 16:33:14

问题


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?


回答1:


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.




回答2:


Try this :

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



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



回答4:


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@



回答5:


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




回答6:


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




回答7:


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


来源:https://stackoverflow.com/questions/12962515/right-padding-with-zeros-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!