将 Char 转换为 double

Conversion Char to double(将 Char 转换为 double)
本文介绍了将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)