Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
463 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...