将 String 中的指数值转换为不带指数表示法的十进制表示

Convert exponential values in a String into a decimal representation without exponential notation

我有一个这样的字符串构建:

String str = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526"

-7.5e-4我想改成-0.00075

我想将指数值更改为十进制值以获得如下内容:

String str = "m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526"

我有很多这样的字符串需要检查和转换。

我真的不知道如何有效地改变指数值,因为所有这些值都在一个字符串中...

如果您知道一种有效且快速的方法,请告诉我。

您可以在 BigDecimal class 中使用方法 toPlainString:

String num = "7.5e-4";
new BigDecimal(num).toPlainString();//output 0.00075

像这样的东西应该可以完成工作:

public static void main(String[] args) {
    String patternStr = "[0-9.-]*e[0-9.-]*";
    String word = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(word);
    if (matcher.find()) {
        Double d = Double.valueOf(matcher.group());
        System.out.println(word.replaceAll(patternStr, BigDecimal.valueOf(d).toPlainString()));
    }

}

输出将是:

m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526

当然,如果字符串上有多个指数,您将不得不稍微调整一下。

您可以使用 Double.parseDouble 进行解析,然后使用 String.format():

进行格式化
    double d = Double.parseDouble("-7.5e-4");
    String s = String.format("%f", d);