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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With