1

I have following string in my java class

String str="0000000000008";

Now I want to increment that so that the next value should be 0000000000009

For that purpose, I tried to cast this String str into Integer

Integer i=Integer.parseFloat(str)+1;

and when I print the value of i it prints only 17(as it removes the leading 0's from string at the time of cast).

How can I increment the String value, so that the leading 0's will remain, and the series will continue?

2 Answers 2

7

Practical solution - use String.format:

str = String.format("%013d", Long.parseLong(str)+1);
Sign up to request clarification or add additional context in comments.

2 Comments

(didn't count the digits ;) it's only 13, not 17)
You could also do str = String.format("%0" + str.length() + "d", Long.parseLong(str)+1); to keep the number of digits in the original string.
5

You are on the correct path. First parse to Long:

long cur = Long.parseLong("0000000000008");

increment and format back to String with leading 0s:

new java.text.DecimalFormat("0000000000000").format(cur + 1);

or alternatively:

String.format("%013d", Long.valueOf(cur));

3 Comments

..Thanks for the answer. But the String str is not a constant. It may be changed during run-time. So, is there any other solution for this?
@ArunKumar: so, what is wrong with: Long.parseLong(knownAtRuntime) where knownAtRuntime is a String variable?
@ Tomasz Nurkiewicz -- You are right. Your answer will work for a constant. But my concern is that this will not work for a String variable whose value may be changed during execution of program.

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.