Convert Integer to String, with leading zeros?

2

I'm manipulating dates, and I need to convert ints to String without losing the number in front.

That is, 01, 02, 03, 04

I've tried String.valueOf() and Integer.ToString() , but it eliminates the zero on the left

thanks in advance

    
asked by Paco 28.10.2018 в 20:48
source

2 answers

2

If the idea is that the number always occupies two positions, complemented on the left with zeros, you should use something like this:

String.format("%02d", miVariableNumerica);

Good luck!

    
answered by 28.10.2018 в 20:52
0

If you want to add a% co_of% of zeros to the left ( padding ), apply a format:

 int valorNumerico = 2;
 String cadena = String.format("%02d" , valorNumerico);

according to the above, leading zeros will have a value of:

02

If you want to eliminate all zeros, one option would be using this cadena

s.replaceFirst("^0+(?!$)", "")

example:

String  cadena = "000012";
cadena = cadena.replaceFirst("^0+(?!$)", "");

the result of REGEX would be:

12
answered by 28.10.2018 в 20:52