2

I am looking for a way to convert a String to Integer or long but I need to keep the leading 0s from the String.

I guess this is not possible, is it?cause numbers do not work like that.

ex: String = "0153" needs to be converted to Integer and it should look like "0153".

Alex
  • 93
  • 1
  • 4
  • 10
  • What is the language? – Franklin Yu Feb 02 '17 at 09:03
  • Why do you need both leading zeros and for it to be an int? 0153 is not a number. – JamesT Feb 02 '17 at 09:05
  • The language is Java and I need the convertion to be done somehow like this because otherwise a big refactoring is supposed to be made in the project I am working on. – Alex Feb 02 '17 at 09:08
  • For integers, 0153 and 153 is the same. Actually, there *is* a lot of leading zeroes in an integer in memory. Leading zeroes only makes difference when you convert it back to a string again. Is it possible to tell more about when it matters? – Franklin Yu Feb 03 '17 at 05:33
  • 1
    I work on a java ee project. In backend I had a string like 0155 which was converted into integer which gave me the 155 output. I had to show this value in the front end with 4 digits and because of the conversion I always lost the leading 0 digit. That was the format which was supposed to be displayed. I adjusted this issue in FrontEnd with JavaScript using string.pad(4, value) which puts 0s in front of the value if there are less that 4 digits, because I could not fix it in the backend with Java. – Alex Feb 03 '17 at 09:47

1 Answers1

0

If you already know the total digits to be displayed, you can figure out how many digits your int is and then append the leading zeros onto the string.

to find the number of digits, you can use 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);

Another solution is How can I pad an integers with zeros on the left?

Community
  • 1
  • 1
Bill F
  • 723
  • 11
  • 23