在将字符串解析为双精度时保持科学记数法

  • 本文关键字:字符串 双精度 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.

下面的代码转换 1e7 正确为 1e7,但 1e4 错误地为 10000

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

双精度没有内在格式,它只是位。你所看到的是在 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);

最新更新