我有一个像这样的字符串:"2E6 3.34e-5 3 4.6",我想用replaceAll来替换像这样的标记:

"((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)"

(即两个带有e或E的数字)转换为等效的普通数字格式(即将"2E6"替换为"2000000",将"3.34e-5"替换为"0.0000334"

我写:

value.replaceAll("((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)", "($1)*10^($6)");


但我想将第一个参数乘以10乘以第二个参数的功效,而不仅仅是这样写..有什么想法吗?

更新

根据您的建议,我进行了以下操作:

Pattern p = Pattern.compile("((\\-)?[0-9]+(\\.([0-9])+)?)(E|e)((\\-)?[0-9]+(\\.([0-9])+)?)");
Matcher m = p.matcher("2E6 3.34e-5 3 4.6");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "WHAT HERE??"); // What HERE ??
}
m.appendTail(sb);
System.out.println(sb.toString());


更新

最后,这是我达到的目标:

// 32 #'s because this is the highest precision I need in my application
private static NumberFormat formatter = new DecimalFormat("#.################################");

private static String fix(String values) {
    String[] values_array = values.split(" ");
    StringBuilder result = new StringBuilder();
    for(String value:values_array){
        try{
            result.append(formatter.format(new Double(value))).append(" ");
        }catch(NumberFormatException e){ //If not a valid double, copy it as is
            result.append(value).append(" ");
        }
    }
    return result.toString().substring(0, result.toString().length()-1);
}

最佳答案

如果您需要将科学数字符号转换为普通形式,则可以使用DecimalFormat

public static void main(String[] args) {
    NumberFormat formatter = new DecimalFormat();

    double num1 = 2E6;
    formatter = new DecimalFormat("##########");
    System.out.println(formatter.format(num1));

    double num2 = 3.3e-5;
    formatter = new DecimalFormat("#.##########");
    System.out.println(formatter.format(num2));
}


只需添加逻辑即可在spaces上分割初始字符串,然后应用上述逻辑。

您可以在DecimalFormat的javadoc中检查有关#之类的符号的更多信息(在本例中为)。

Symbol Location     Localized?  Meaning
------------------------------------------------------------
#      Number       Yes         Digit, zero shows as absent

07-24 15:48