views:

56

answers:

4

hello,

how can i get for example the integer codeInt=082 from String code='A082' i have tried this:

int codeInt = Integer.parseInt(code.substring(1,4));

and i get codeInt=82 ,it leaves the first 0 but i want the full code '082'.

i thought of parseInt(String s, int radix) but i don't know how .

any help will be appreciated .
thanks.

+2  A: 

An integer just stores a number. The numbers 82 and 082 (and 0082 and 000000082 for that matter) are exactly the same (unless you put them into source code in some languages in that manner, then you'll get a compiler error)1.

If you desperately need the leading zero, then you should either leave it as a string, or format the number appropriately for output later.


1 Due to the C designers having the ingenious idea that writing octal constants with a preceding zero would be cool. As if something like 0o123 would have been that hard to implement once you already got 0xf00 ...

Joey
A: 

If you want 0000123 then you need to threat a variable as a String instead of Integer. Simply: 123 is equal to 000123 and 0123 and 0000...1 billion zeros here...000123.

But if you just want to display a number with fixed length then use System.out.format().

Crozin
A: 

The number 82 and 082 and 0082 is mathematically the same number, and is represented by the same sequence of bits. You can't encode the number of leading zeroes in an int (although you can certainly print it with whatever format you choose).

Note also that the number 082 is different from the Java literal 082, which is an (invalid) octal literal.

int i = 010;
System.out.println(i); // this prints 8
polygenelubricants
+1  A: 

082 is not an integer. It's a string representing the integer 82. If you require leading zeros to be left untouched, you will need to work with strings. If you only need it to print 082, you can use java.text.MessageFormat or System.out.format() or other, similar solutions to print it that way.

Thomas Lötzer
+1 - you said it dude!
Webbisshh