【问题标题】:How to format numbers to same number of digits, 0-padded?如何将数字格式化为相同的位数,0填充?
【发布时间】:2011-07-21 03:35:25
【问题描述】:

我有几个不同长度的字符串

"2323"
"245"
"353352"

我需要将它们转换为相同大小的字符串,例如:

"0002323"
"0000245"
"0353352"

如何在每个字符串前面自动添加正确数量的 0?

谢谢

【问题讨论】:

  • 如果输入字符串比预期的输出格式长怎么办?
  • 您还可以计算字符串中字符/数字的数量,然后将所需数量的值附加到前面,可以是 0 或空格或任何其他字符。

标签: java format


【解决方案1】:

使用String.format:

Integer i = Integer.valueOf(src);
String format = "%1$07d";
String result = String.format(format, i);

【讨论】:

  • 嗯好的。但是在我的情况下 src 已经是一个字符串而不是一个整数。我应该转换 string > int > string 吗?
【解决方案2】:

使用DecimalFormatString.formatprintf,您可以格式化数字。

使用 DecimalFormat 的示例:

NumberFormat formatter = new DecimalFormat("0000000");
String number = formatter.format(2500);

希望对你有帮助。

问候!

【讨论】:

    【解决方案3】:

    或使用Apache Commons / Lang

    String s = "245";
    String zeroPadded = StringUtils.leftPad(s, 6, '0');
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 2011-12-23
      • 2020-10-12
      相关资源
      最近更新 更多