Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 606
user14190471 Avatar asked Oct 18 '20 09:10

user14190471


People also ask

Can we convert string to int in Java?

We can convert String to an int in java using Integer. parseInt() method. To convert String into Integer, we can use Integer. valueOf() method which returns instance of Integer class.

Can we convert character to integer in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


4 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)));
like image 88
Federico klez Culloca Avatar answered Nov 14 '22 21:11

Federico klez Culloca


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
like image 44
Majed Badawi Avatar answered Nov 14 '22 22:11

Majed Badawi


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

like image 38
Varun Sharma Avatar answered Nov 14 '22 22:11

Varun Sharma


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

like image 25
eskapynk Avatar answered Nov 14 '22 21:11

eskapynk