将 Char 转换为 double

2023-04-05Java开发问题
11

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

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13