简体   繁体   中英

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[] 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;

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. It is just a number.

If you want the printout to include a leading zero, I recommend using String#format() . To always get a leading 0 if part1Int is below 10 , use:

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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