demouser123
demouser123

Reputation: 4264

How to add leading zeros in a string of numbers to complete it to become a required 9 digit number

I have to automate a scenario in Selenium in which I am required to pick values from an excel file and then to input that in the login fields of the webpage. There is a check to be placed in the first value to be picked, which I am unable to complete.

Suppose I am picking up values 103030, from the first row, first column. Now this is a six digit number. The webpage field where I am supposed to enter this checks for a minimum 9 digit number.

So, if it is a six, or a seven digit number, I have to concatenate leading zeros for the remaining places.

For example,in this scenario, 103030 is a 6 digit number, and it requires three more digits to become a 9 digit number. So I have to add three leading zeros to this- like 000103030. Similarly if it is a seven digit number- like 1030303, then I have to add 001030303.

How can this be achieved.

The way I thought it can be achieved is by finding the number of digits, subtracting that by 9 and then replacing the required number with zeroes, but I'm struggling with the logic for adding leading zeroes.

Upvotes: 0

Views: 1913

Answers (3)

mystarrocks
mystarrocks

Reputation: 4088

There's not a great deal of logic involved here. If you need something elegant, try the StringUtils#leftPad.

This is included in the commons-lang apache library.

Upvotes: 0

shri046
shri046

Reputation: 1198

Check this thread for left padding a string. As mentioned in the above answer you can use String.format(..) or if your project depends on Apache commons library you can use StringUtils.leftPad(....).

Upvotes: 2

William Helgeson
William Helgeson

Reputation: 136

Use String.format (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax)

Your case would use: String.format("%09d", number)

Upvotes: 2

Related Questions