Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

java - Conversion Char to double

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...