-5
String s = 000000001;
String e = 009999999;

Convert String 000000001 to Integer 000000001.

I tried doing this with Integer.parseInt

int n = Integer.parseInt(s);

I am getting n = 1, but I want n should have 000000001

for (int ind = Integer.valueOf(s); ind < Integer.valueOf(e); ind++)  {

  String pp = "ggg" + ind; // I want pp should be like this- ggg000000001 and it keep on increasing like   ggg000000002, then ggg000000003 and etc etc.   
}
AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • What would all those leading zeros mean in an `Integer`? Do you want to _format the output_ differently? – sarnold May 01 '12 at 23:06
  • 14
    That doesn't make sense; leading zeros don't exist in an integer, they only exist in a string. I assume you are asking "how do I format the output when I display an integer?". – Oliver Charlesworth May 01 '12 at 23:06
  • 1
    The integer 000000001 does not exist – Edwin Dalorzo May 01 '12 at 23:06
  • 5
    `String s = 009999999;` Err... what? Did you try to compile that? You probably want some quotes there. – Mark Byers May 01 '12 at 23:07
  • If you were to convert the String `000000001` into an integer somehow, it would be considered to be an **octal** number (with leading zeros). – Lion May 01 '12 at 23:08
  • All : this is a valid question - in some countries numbers may be shown this way. Also, sometimes data has to be standardized. `001, 012, 123` looks better than `1, 12, 123` – Caffeinated May 01 '12 at 23:12
  • The integer "1" *is* the integer "00000001". If you want to *represent* "1" as "0000001", then look at Bohemian's "format()" example. – paulsm4 May 01 '12 at 23:14
  • 1
    @Adel: The underlying problem is valid, but the way the question is phrased doesn't make sense. – Oliver Charlesworth May 01 '12 at 23:14

2 Answers2

9

The integer 000000001 is 1. I can only assume you want to display 1 as 000000001. This is how you do it:

System.out.format("%09d", n);

Here's a little test:

public static void main(String[] args) throws Exception {
    String s = "000000001";
    int n = Integer.parseInt(s);
    System.out.format("%09d", n);
}

Output:

000000001


FYI System.out.format() is a convenience facade for System.out.println(String.format()), so if you need the String in your code (and don't want to output it) use:

String s = String.format("%09d", n);

Updated due to question update:

String pp = String.format("ggg%09d", ind);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

You may use the class DecimalFormat to do this:

DecimalFormat myFormatter = new DecimalFormat(pattern); 
String output= myFormatter.format(value); 
System.out.println(value + " " + pattern + " " + output);

See this question too: Add leading zeroes to number in Java?

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216