将Char转换为double [英] Conversion Char to double

查看:1027
本文介绍了将Char转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将char形式的数值转换为double值?

How may I convert a numerical value in the form of a char to a double value?

我尝试将char强制转换为double但是。 。它不像我猜的那样工作,因为像char这样的字符'4'将转换为双精度的52.0。

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.

那么有一种方法可以将具有
char c ='4'
值的char转换为4.0的双精度值,其中我真的可以对值进行数学计算吗?

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?

这只是我创建的一个小程序,用于显示将数字char直接转换为double不会起作用

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);
}
}

输出:

56.0
52.0
1.0769230769230769


推荐答案

您可以这样做:

double d2 = (double) Character.digit(eight, 10);
double d1 = (double) Character.digit(four, 10);

或:

double d2 = (double) (eight - '0');
double d1 = (double) (four - '0');

如果要转换整个字符串,请使用 Double.parseDouble

If you want to convert a whole string, use Double.parseDouble

double d2 = Double.parseDouble("15.5");

当心可能的 NumberFormatException 是字符串是无效的浮点数

Beware of a possible NumberFormatException is the string is an invalid floating point number

这篇关于将Char转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆