简体   繁体   English

从字符串转换为整数时丢失前导“ 0”零

[英]Losing leading “0” Zeros when converting to integer from string

I am losing the leading zeros from my variable when I am converting it from a String to an Integer , 当我将变量从String转换为Integer ,我失去了前导零。

String[] parts = Firsttt.split(":");
String part1 = parts[0]; // Hour
String part2 = parts[1]; // Minute
Integer part1int = (Integer.valueOf(part1));
part1int++;
Firsttt = part1int +":"+ part2;

Is there a correct way to do this without loosing the leading zero or should I just alter the result to include the zero again ? 是否有一种正确的方法可以做到这一点而又不丢失前导零呢?还是应该只改变结果以再次包括零?

ie: Firsttt = "0" + part1int +":"+ part2; 即: Firsttt = "0" + part1int +":"+ part2;

the problem with adding the zero again is that the variable doesn't always include a zero so just checking that there isn't a better way. 再次添加零的问题在于变量并不总是包含零,因此只需检查是否有更好的方法即可。 Thank you 谢谢

An Integer doesn't have leading zeros, or any other formatting property. Integer没有前导零或任何其他格式设置属性。 It is just a number. 它只是个数字。

If you want the printout to include a leading zero, I recommend using String#format() . 如果您希望打印输出包含前导零,我建议使用String#format() To always get a leading 0 if part1Int is below 10 , use: 要在part1Int小于10始终得到前导0 ,请使用:

String.format("%02d:%s", part1Int, part2);

if you don't want to go for a fancy String.format() , you can use your own way as 如果您不想花哨的String.format() ,可以使用自己的方式

if (part1int / 10 > 0) {
    Firsttt = part1int + ":" + part2;
} else {
    Firsttt = "0" + part1int + ":" + part2;
}

当且仅当part1int小于10时,您才可以添加前导零;或者使用填充0的某些格式:

Firsttt = String.format("%02d:%d", part1int, part2); 

try 尝试

Firsttt = String.format("%02d:%s", part1int, part2);

this will add the leading zeros if necessary . 如有必要,这将添加前导零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM