This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Converting string to int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting string to int" Watch "Converting string to int" New topic

Converting string to int

sridhar row
Ranch Hand

Joined: Jan 16, 2008
Posts: 162
If I have a String containing "0123", how do I convert it to an integer

I've tried all kinds:
int i = Integer.parseInt("0123"),
int a = new Integer("0123").intValue();
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

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Rob Spoor

Joined: Oct 27, 2005
Posts: 19655

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).

How To Ask Questions How To Answer Questions
subject: Converting string to int
Similar Threads
Formatting numbers in a String
setMinimumIntegerDigits problem
negative numbers
Threads Question
Question on Thread k&b q.5 pg 735