将 Char 转换为 double

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

问题描述

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

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

我尝试将 char 转换为双精度,但是...它不像我猜测的那样工作,因为诸如 '4' 之类的 char 将在双精度中转换为 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.

那么有没有办法转换一个值为say的char字符 c = '4'到 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?

这只是我创建的一个小程序,目的是表明将数字字符直接转换为双精度不会像我预期的那样工作.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在 Java 中自动将输入字符转换为大写 下一篇:为什么一个 char + 另一个 char = 一个奇怪的数字

相关文章