将字符串转换为int或long,但保持前导零

时间:2017-02-02 09:01:54

标签: leading-zero

我正在寻找一种将String转换为Integer或long的方法,但我需要保留String中的前导0。

我想这是不可能的,是吗?因为数字不能那样工作。

ex:String =“0153”需要转换为Integer,它应该看起来像“0153”。

1 个答案:

答案 0 :(得分:0)

如果您已经知道要显示的总位数,您可以计算出int的位数,然后将前导零附加到字符串上。

要查找位数,您可以使用int length = (int)Math.log(number)+1;

String string;
for(int i=0; i<4-length; i++){ //the 4 is the number of digits you want. adjust accordingly
   string.append(0);
}
string.append(number);

另一个解决方案是How can I pad an integers with zeros on the left?