• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting string to int

 
sridhar row
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a String containing "0123", how do I convert it to an integer
variable?

I've tried all kinds:
Integer.valueOf("0123"),
int i = Integer.parseInt("0123"),
int a = new Integer("0123").intValue();
etc
permutations but always end up with a int value 123 instead of 0123

What's the trick?
[ February 10, 2008: Message edited by: sridhar row ]
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no "trick". The leading zero is not significant, and is not part of the textual representation of the int 123. If it is necessary to display a leading zero, you can do so with a NumberFormat object, or using String.format().
[ February 10, 2008: Message edited by: Garrett Rowe ]
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not necessarily true.

The leading 0 could mean that the number should be octal instead of decimal, just as 0x is the prefix for hexidecimal.

If that is the case, use Integer.parseInt("0123", 8). The result would be 83. Integer.parseInt("0123") is similar to Integer.parseInt("0123", 10).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic