解析没有尾数和指数分隔符的双精度

时间:2018-11-30 16:04:31

标签: java double

我必须从以下格式的数据文件中读取双份

1.234+5 // = 1.234e+5
1.234-5 // = 1.234e-5

我无法更改格式,我必须从数据文件中解析数百万(=方法应该是有效的)。

我可以提供十进制格式还是有一种方便的方法(可在Java jdk中使用)解析这些双精度数?

Double.parseDouble("1.234+5"); // throws NumberFormatException
Scanner scanner = new Scanner("1.234+5");
Scanner.nextDouble(); // throws InputMismatchException

编辑1 我所说的数据文件的精度: 数据文件是ENDF格式的文件,格式非常严格(手册共300页),以下是其中一个文件的摘录

9.223500+4 2.330248+2          0          0          0          63515 8457
2.22102+16 1.57788+13          0          0          6          03515 8457
4.170051+4 1.312526+3 1.641191+5 1.625818+3 4.413323+6 1.648523+53515 8457

我可以用一个简单的

解析整数
Integer.parseInt()

但是我不能加倍。

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式插入e,然后以常规方式对其进行解析:

private static final Pattern INSERT_EXPONENT = Pattern.compile("(.*)([+-].*)");

System.out.println(INSERT_EXPONENT.matcher("1.234+5").replaceFirst("$1e$2"));
System.out.println(INSERT_EXPONENT.matcher("1.234-5").replaceFirst("$1e$2"));

这只是快速而肮脏,并不能防止输入无效。

答案 1 :(得分:2)

这是我的尝试。我不知道这是否是您要的内容,但这会将数字转换为双精度格式。希望这会有所帮助。

    String temp = "1.234+5";
    StringBuilder str = new StringBuilder(temp);
    for(int index = temp.length() - 1; index > 0; index--)
    {
        //this will look for a + or - symbol in your string
        if(temp.charAt(index) == '+' || temp.charAt(index) == '-') {
            str.insert(index, 'e');  //this will insert e before the symbol
            break;
        }
    }
    temp = str.toString();
    System.out.println(temp);
    double a= Double.parseDouble(temp); //convert the string back to a double 
    System.out.println(a); //this is just to test the output

    double b = 1.234e+5;
    System.out.println(b);

答案 2 :(得分:1)

您可能需要一个正则表达式。

private void test() {
    String [] test = {"1.234+5", "-1.234-2"};
    for (String s : test) {
        System.out.println(s + " -> " + parse(s));
    }
}

private static final Pattern FindMissingE = Pattern.compile("([+-]{0,1}[0-9.]+)([+-]{0,1}[0-9]+)");
private double parse(String s) {
    Matcher m = FindMissingE.matcher(s);
    if(m.find()) {
        return Double.parseDouble(m.replaceFirst("$1e$2"));
    }
    return 0.0;
}