Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将字符串解析为双精度字符串时,请保留科学符号_Java - Fatal编程技术网

Java 将字符串解析为双精度字符串时,请保留科学符号

Java 将字符串解析为双精度字符串时,请保留科学符号,java,Java,我正在使用Double.parseDouble()将用户输入从字符串转换为科学符号。但我注意到,这仅适用于以下范围: value with exponent number >=7 (ie: 1e7) for positive exponent or value with exponent number <= -4 (ie: 1e-4) for negative exponent. double没有内在的格式,它只是位。您看到的是对双精度计数器调用toString()的结果。默认情况

我正在使用
Double.parseDouble()
将用户输入从字符串转换为科学符号。但我注意到,这仅适用于以下范围:

value with exponent number >=7 (ie: 1e7) for positive exponent or
value with exponent number <= -4 (ie: 1e-4) for negative exponent.

double没有内在的格式,它只是位。您看到的是对双精度计数器调用toString()的结果。默认情况下,Double.toString()仅在某些情况下使用科学记数法。如果要在将其转换为字符串以供显示时使用特定的符号,请再次使用十进制格式

public Double convert(String value){
    DecimalFormat df = new DecimalFormat("0.##E0");
    String formattedVal = df.format(value);      
    return Double.parseDouble(formattedVal);
}

DecimalFormat df = new DecimalFormat("0.##E0");
Double d = convert("1e4");
String dAsString = df.format(d);
System.out.println(dAsString);

double没有格式化的概念。如果你想要一个特定的表示,你应该在转换回字符串时应用相关的格式。我不知道你想要什么作为输出。你说它只在某个范围内“起作用”,但你想要什么范围,每个范围需要什么输出?@Oliver这就是我使用DecimalFormat类无法完成的原因。Java(和大多数浮点实现)没有附加“格式”的概念。一旦将数字解析为双精度,它就不再具有格式。@t如果您在解析字符串时使用的是DecimalFormat类,而不是将双精度转换回字符串以供显示,则使用DecimalFormat类。感谢您澄清此问题。现在我明白了问题的根源。
public Double convert(String value){
    DecimalFormat df = new DecimalFormat("0.##E0");
    String formattedVal = df.format(value);      
    return Double.parseDouble(formattedVal);
}

DecimalFormat df = new DecimalFormat("0.##E0");
Double d = convert("1e4");
String dAsString = df.format(d);
System.out.println(dAsString);