1

I get gpnString as a String and I have to parse it to an int.
I was using Integer.parseInt(gpnString) but gpnString contains leading zeros and they get removed with Integer.parseInt().

The gpnString has allways the length of 8 so I tried to add so many 0 as needed but the int detects it as NULL so it does not add the number 0. This is my Code:

int parseToInt(String gpnString) {
        int gpn = Integer.parseInt(gpnString);
        for (int addZero = 8 - String.valueOf(gpn).length(); addZero != 0; addZero--) {
            gpn = 0 + gpn;
        }
        return gpn;
}

/*
  Input : gpnString = "00012345"
  Output: 12345
*/

I have looked this up on Stackoverflow but I only found an answer like this:

String gpn = String.format("%08d" , gpnSring);

I have tried it but you get a String so I would have to parse it again and this would lead to the exact same Problem as before.

Edit:
I heard an Integer or int can not have leading zeros...
I use the gpn for personal identification in a Database. Would the best Idea be to edit the grafical output so it just looks like it has the 0? Or is there a better way to solve this?

2
  • 3
    An integer does not have leading zeroes. The integer value of 01 is 1. There's no way to store leading zeroes in an int or Integer. Commented Jun 10, 2020 at 7:01
  • 3
    Partial aside: if you write an int literal starting with zero, it's actually an octal literal. So 010 is actually equal to 8. Commented Jun 10, 2020 at 7:04

1 Answer 1

2

An integer can't have leading zeros.

As leading zeros add no mathematical significance for an integer, they will not be stored as such. Leading zeros most likely only add to the readability for the human viewing / processing the value. For that usage a string can be used in the way you already found yourself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.