本文介绍了在 Java 中为数字添加前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更好的方法来获得这个结果?如果 num 的数字多于数字,则此函数将失败,我觉得它应该在库中的某个地方(例如 Integer.toString(x,"%3d") 或其他内容)
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
推荐答案
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
在您的情况下,它将是:
In your case it will be:
String formatted = String.format("%03d", num);
- 0 - 用零填充
- 3 - 将宽度设置为 3
这篇关于在 Java 中为数字添加前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!