如何在左侧填充带零的整数? [英] How can I pad an integer with zeros on the left?

查看:261
本文介绍了如何在左侧填充带零的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中转换为 String 时,如何用零填充 int

How do you left pad an int with zeros when converting to a String in java?

我基本上希望用前导零填充最大 9999 的整数(例如1 = 0001 )。

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

推荐答案

使用 java.lang。 String.format(String,Object ...) 像这样:

Use java.lang.String.format(String,Object...) like this:

String.format("%05d", yournumber);

用于零填充,长度为5.对于十六进制输出,请替换 d x ,如%05x

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

完整格式化选项记录为 java.util.Formatter

The full formatting options are documented as part of java.util.Formatter.

这篇关于如何在左侧填充带零的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆