问题
How may I convert a numerical value in the form of a char to a double value?
I've tried just casting the char to a double but... it doesn't work like that I'm guessing as char such as '4' will convert to 52.0 in doubles.
So is there a way to convert a char with a value of say char c = '4' to a double value of 4.0 where I can actually perform mathematical calculations on the value?
This is just a little program I created to show that casting a numeric char directly to a double won't work the way I was expecting.
public class conversion
{
public static void main(String args[])
{
char eight = '8';
char four = '4';
double d2 = (char)eight;
double d1 = (char)four;
System.out.println(d2);
System.out.println(d1);
double result = (d2 / d1);
System.out.println(result);
}
}
outputs:
56.0
52.0
1.0769230769230769
回答1:
You can do:
double d2 = (double) Character.digit(eight, 10);
double d1 = (double) Character.digit(four, 10);
Or:
double d2 = (double) (eight - '0');
double d1 = (double) (four - '0');
If you want to convert a whole string, use Double.parseDouble
double d2 = Double.parseDouble("15.5");
Beware of a possible NumberFormatException is the string is an invalid floating point number
回答2:
You can subtract '0' then cast as a double:
char c = '8';
double d = (double) (c - '0'); // <--
System.out.println(d);
8.0
You can check that c is valid via '0' <= c && c <= '9'.
回答3:
You can also use :
double d2 = Double.valueOf(String.valueOf(eight));
double d1 = Double.valueOf(String.valueOf(four));
回答4:
When you cast like that it returns the ASCII code of 4 or 8. The following code is what you want:
char myc='4';
double myd= Double.parseDouble(Character.toString(myc));
回答5:
The character '0' does not correspond to the integer 0. It corresponds to the ASCII key code for the '0' character. Fortunately, the key codes for the characters '0' through '9' are sequential, so you can simply subtract '0' to convert a numeric character to the integer number it represents:
double d2 = (char)(eight - '0');
double d1 = (char)(four - '0');
回答6:
How about this?
char doubleChar = '8';
double doubleDouble = Double.parseDouble(Character.toString(doubleChar));
回答7:
You need to convert the char to a string and then to double like this:
double d2 = Double.parseDouble(Character.toString(eight));
double d1 = Double.parseDouble(Character.toString(four));
来源:https://stackoverflow.com/questions/19987628/conversion-char-to-double