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?
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?
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
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
}
int foo = Integer.parseInt("1");
//foo now equals 1