Home > other >  Java: When converting an integer to String, whenever there is a zero in the front of the integer it
Java: When converting an integer to String, whenever there is a zero in the front of the integer it

Time:01-16

Making a program needed to change from integer to string but there is a case where if it has a 0 in the front, it just doesn't show up in the string which messes up the program since it is supposed to have the length at 4 but if it is 0234 it would be counted as only 3 characters.

I tried out different ways to convert it from int to String using StringBuilder, valueOf, toString, and some other ways that I found but I couldn't figure out how to fix the problem.

My Work

Is there anything I could do to fix or get around it?

CodePudding user response:

As in mathematics, in Java, 0 in front of a number are considered non significant.

015, 000015 or 15 are the exact same number and are actually "stored" as 15.

If you want to preserve the zeros, you need to read your input as a String.

CodePudding user response:

If you want 4 digits, with 0 filling any missing numbers at the start, use String.format("d", encrypt).

  •  Tags:  
  • java
  • Related