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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chriss
  • 1,011
  • 1
  • 13
  • 22
  • 3
    Did you see String API? – Rohit Jain Sep 30 '13 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`. – Obicere Sep 30 '13 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. – Hot Licks Sep 30 '13 at 20:24
  • @HotLicks it will be extremely useful if he wishes to create his own method for parsing it. – Obicere Sep 30 '13 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.) – Hot Licks Sep 30 '13 at 20:33

5 Answers5

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
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
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
}
Moob
  • 14,420
  • 1
  • 34
  • 47
6

Integer.parseInt does exactly that.

int foo = Integer.parseInt("1");
federico-t
  • 12,014
  • 19
  • 67
  • 111
4
int foo = Integer.parseInt("1");
//foo now equals 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
user446836
  • 733
  • 4
  • 16
  • 24
2
String s = "1";
int i = Integer.valueOf(s);
Mureinik
  • 297,002
  • 52
  • 306
  • 350