【问题标题】:How to format a 3-digit integer to a 4-digit string? [duplicate]如何将 3 位整数格式化为 4 位字符串? [复制]
【发布时间】:2013-07-17 10:08:58
【问题描述】:

我想将 3 位数的 integer 格式化为 4 位数的 string 值。示例:

int a = 800;
String b = "0800";

当然,格式化将在String b 语句中完成。谢谢大家!

【问题讨论】:

标签: java


【解决方案1】:

使用String#format:

String b = String.format("%04d", a);

其他格式请参考documentation

【讨论】:

  • 废话,差不多 24 小时,我完全忘了接受这个答案!我的错!
【解决方案2】:

如果您只想拥有它一次,请使用String.format("%04d", number) - 如果您更频繁地需要它并且想要集中模式(例如配置文件),请参阅下面的解决方案。

顺便说一句。有一个关于数字格式的 Oracle tutorial。

简而言之:

import java.text.*;

public class Demo {

   static public void main(String[] args) {
      int value = 123;
      String pattern="0000";
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(output); // 0123
   }
}

希望对您有所帮助。 *约斯特

【讨论】:

  • 这实际上可能会好一些。
【解决方案3】:
String b = "0" + a;

会不会更容易些?

【讨论】:

  • @SandiipPatil 这不会编译。
  • 能更简单点吗?不。但也许更健壮/灵活。
  • @Thilo:同意。但这个问题专门要求 3 位整数。当事情可以很简单时,为什么要让事情变得复杂?现在,我也同意您的解决方案远非复杂:-)
  • 我认为我们的两种解决方案都可能存在负数问题。让我们把它作为练习留给读者。
  • @SandiipPatil Euh..."0" + a 工作得很好...
【解决方案4】:

请尝试

String.format("%04d", b);

【讨论】:

  • 除了b 而不是a,这个答案与Thilo 的答案有何不同?
  • @MarounMaroun:好吧,看看时间戳。很可能只是一个竞争条件。
【解决方案5】:

您可以随时使用Jodd Printf。在你的情况下:

Printf.str("%04d", 800);

会做这项工作。此类是在 Sun 添加 String.format 之前创建的,并且具有更多格式选项。

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多