Java中的零填充 [英] Right padding with zeros in Java
问题描述
很抱歉,如果这个问题已经提出,我已经进行了深入搜索,什么也没做.
Sorry if this question was made already, I've made a deep search and nothing.
现在,我知道:
String.format("%05d", price);
将价格用左边的零填充,所以价格25将导致 00025
Will be padding my price with zeros to the left, so a price of 25 will result in 00025
如果我想将其右移,结果为 25000 ,该怎么办?如何仅使用 String.format 模式来做到这一点?
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?
推荐答案
您可以使用:
String.format("%-5s", price ).replace(' ', '0')
我可以只使用格式模式吗?
Can I do this using only the format pattern?
String.format
使用Formatter.justify
就像String.printf
方法一样.
从此帖子中,您将看到输出空间很硬编码,因此必须使用String.replace
.
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.
这篇关于Java中的零填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!