12
String val = "98"

我需要将输出设为0000098(7 位)。

我需要将零填充到字符串或整数值...

val 中存储的数字是动态的,可以包含任意位数,但输出应始终为 7 位。

4

4 回答 4

25

在 groovy 中,您可以像这样填充字符串:

val.padLeft( 7, '0' )

这将用零填充字符串的左侧,直到长度为 7 个字符

于 2012-07-13T08:25:08.020 回答
14

使用String.format

public class A {
  public static void main(String[] args) {
    System.out.println(String.format("%07d", 98)); // -> 0000098
  }
}
于 2012-07-13T08:02:40.740 回答
0

您可以通过以下方式使用 NumberFormat 格式化您的 String 值:

NumberFormat formatter = new DecimalFormat("0000000");

这意味着您的 String 将根据需要以 0 完成。

然后,要格式化您的字符串,您可以执行以下操作:

String formatRes = formatter.format(new Double(val));

因为“格式”方法需要一个双精度参数。

于 2012-07-13T08:07:15.140 回答
0

看看http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html它提供了类似的功能leftpadrightpad...

于 2012-07-13T08:00:56.687 回答