43

I have "1" as a string, and I would like to convert it to decimal, 1, as integer.

I tried charAt(), but it returns 49, not 1 integer.

So, what is required to convert the "1" string to 1 integer?

5
  • 3
    Did you see String API? Commented Sep 30, 2013 at 20:19
  • 2
    49 is the numerical equivalent for the character 1. To get the numerical value of a single character, you can do this: c - '0'. So, '1' - '0' = 1. Commented Sep 30, 2013 at 20:19
  • @Obicere - Yep, while that's almost certainly not what the OP wanted, it's worthwhile to point it out. An important step in understanding the difference between a (conceptual) number and it's physical representation. Commented Sep 30, 2013 at 20:24
  • @HotLicks it will be extremely useful if he wishes to create his own method for parsing it. Commented Sep 30, 2013 at 20:27
  • @Obicere - Yes, especially if his instructor assigns him the task of writing a number parser from scratch. (And it seems to be a popular assignment, and one that many folks break their pick on.) Commented Sep 30, 2013 at 20:33

5 Answers 5

28

Use Wrapper Class.

Examples are below

int

int a = Integer.parseInt("1"); // Outputs 1

float

float a = Float.parseFloat("1"); // Outputs 1.0

double

double a = Double.parseDouble("1"); // Outputs 1.0

long

long a = Long.parseLong("1"); // Outputs 1
Sign up to request clarification or add additional context in comments.

1 Comment

Or Float, or Double, depending on the type of data.
8
int one = Integer.parseInt("1");

Ideally you should be catching errors too:

int i;
String s = "might not be a number";
try {
   i = Integer.parseInt(s);
} catch (NumberFormatException e) {
   //do something
}

Comments

6

Integer.parseInt does exactly that.

int foo = Integer.parseInt("1");

Comments

4
int foo = Integer.parseInt("1");
//foo now equals 1

Comments

2
String s = "1";
int i = Integer.valueOf(s);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.