How do you turn the first (numerical) character of a string into an integer in Java?

Viewed 117

So let's say I have a double which is 1.5, and then I convert it to a string, then try to turn the first character into a string using the char.at method.

double a = 1.5;
String b = String.valueOf(a);
System.out.println(Integer.valueOf(b.charAt(0)));

But when I did that, here's the output I received:

49

What did I do wrong?

6 Answers

valueOf takes either an int or a String. You passed a char (returned by charAt) which got promoted to an integer. You can use substring to get the first character of the string instead.

double a = 1.5;
String b = String.valueOf(a);
System.out.println(Integer.valueOf(b.substring(0, 1)));

It's taking the ascii value of the first character.

If you want to pass Integer.valueOf a String as a parameter, try the following:

double a = 1.5;
String b = String.valueOf(a);
System.out.println(Integer.valueOf(Character.toString(b.charAt(0))));

Also, if you want to pass an integer, Integer.valueOf can also be used as following:

double a = 1.5;
String b = String.valueOf(a);
System.out.println(Integer.valueOf(Character.getNumericValue(b.charAt(0))));

Output:

1

Just use Character.getNumericValue(b.charAt(0)); to get actual value instead of ASCII

There are various methods to do this, one is the following (using the Double class):

Double number = 1.5;
System.out.println(number.intValue());

The intValue() method will return the int representation of the istance of Double

parseInt will work too:

double a = 1.5;
String b = String.valueOf(a);
int c = Integer.parseInt(b.substring(0,1));
System.out.println(c);

The ASCII value of '1' is 49 which is what you are getting. In order to get 1, you need to subtract '0' or 48 (the ASCII value of '0') from it.

public class Main {
    public static void main(String[] args) {
        double a = 1.5;
        String b = String.valueOf(a);
        System.out.println(b.charAt(0) - '0');
    }
}

Output:

1

Alternatively, you can use Character#getNumericValue to get the numeric value of the character.

public class Main {
    public static void main(String[] args) {
        double a = 1.5;
        String b = String.valueOf(a);
        System.out.println(Character.getNumericValue(b.charAt(0)));
    }
}

Output:

1
Related