Right pad with zeros

情到浓时终转凉″ 提交于 2019-11-27 14:19:35
Reimeus

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

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@

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

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

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