java - 在 int java 前面添加零

标签 java string

如果 int 的字符串等效长度小于 6,我想在其前面添加零。与 String.format 类似。示例:

int e = 21;
System.out.println(String.format("%06d", e)); //000021
int e = 3564;
System.out.println(String.format("%06d", e)); //003564

我需要的是上述输入210000356400末尾添加零。是否已经实现了一些可以完成这项工作的东西,或者我需要自己编写代码?如果是这样如何处理可变长度?

最佳答案

while (e < 100_000) e *= 10;

不言自明。我认为没有比这更简单的方法了。

编辑: 由于e可以为0,我将上面的语句包装到一个函数中:

public static String pad(int input) {
  if (input == 0) return "000000";
  while (input < 100_000) input *= 10;
  return "" + input;
}

关于java - 在 int java 前面添加零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044204/

相关文章:

java - 使用其他项目的 JAR 时出现 NoClassDefFoundError

java - 如何添加使用 JAVA 而不是 odbc32.exe 连接到 MS DB 的新系统 DSN?

python - 在unicode字符串中转换字节字符串

c++ - 运行 Brute Force 算法时出错?

java - 防止命令行参数显示在 bash 历史记录或带有 bash 脚本的 ps -ef 中

java - ImageIcon 不显示在 java 中

Python - 要列出的字符串

python - 从 Python 中的字符串中删除辅音

python - 字典控制 turtle 的运动

java - Android achartengine : Cannot draw multiple lines in a graph