简体   繁体   English

错误解析双Java

[英]error parsing double java

I have this code: 我有以下代码:

public void refreshResources(){
    try{
        String res = driver.findElement(By.cssSelector("#resources_metal")).getText();
        System.out.println("Metal read: " + res);
        res = res.replaceAll("\\u002e", ""); //Removes dots
        System.out.println("Metal without dots: " + res);
        this.metRes = Double.parseDouble(res);
        System.out.println("Converted Metal: " + metRes);
    }catch(NoSuchElementException error){
        System.out.println("Error please try again");
    } 

This is my output: 这是我的输出:

Metal read: 47.386.578 金属版阅读:47.386.578

Metal without dots: 47386578 金属不带点:47386578

Converted Metal: 4.7386578E7 换算金属:4.7386578E7

the question is, why do I have that "E7" at the end of my converted metal? 问题是,为什么转换后的金属末尾有“ E7”? Thanks in advance. 提前致谢。

the "Ex" where "x" is a number, means Exponential. “ Ex”(其中“ x”是数字)表示指数。 So in your case, the number "4.7386578E7" will be "47386578". 因此,在您的情况下,数字“ 4.7386578E7”将为“ 47386578”。 Just take right the dot 7 places. 只需正确点7个位置即可。

However, if you want to print the number with no exponential notation, you can use "printf" in the last print, just like the next code: 但是,如果要打印不带指数符号的数字,则可以在下一个打印中使用“ printf”,就像下面的代码一样:

public void refreshResources(){
try{
    String res = driver.findElement(By.cssSelector("#resources_metal")).getText();
    System.out.println("Metal read: " + res);
    res = res.replaceAll("\\u002e", ""); //Removes dots
    System.out.println("Metal without dots: " + res);
    this.metRes = Double.parseDouble(res);
    System.out.printf("Converted Metal: %.0f", metRes);
}catch(NoSuchElementException error){
    System.out.println("Error please try again");
}

%.0f means that you want to print a float value with no decimal part. %.0f表示您要打印不带小数部分的浮点值。

I hope this answer helps you. 希望这个答案对您有所帮助。

Instead of primitive double or float use "BigDecimal" of "java.math" package. 代替原始的double或float使用“ java.math”包的“ BigDecimal”。 This will give you more precise output. 这将为您提供更精确的输出。 Please see the snippet used below. 请查看下面使用的代码段。

try{
    String res = driver.findElement(By.cssSelector("#resources_metal")).getText();
    System.out.println("Metal read: " + res);
    res = res.replaceAll("\\u002e", ""); //Removes dots
    System.out.println("Metal without dots: " + res);
    this.metRes = Double.parseDouble(res);
    System.out.printf("Converted Metal: %.0f", metRes);
    BigDecimal bigDecimal = new BigDecimal(res);
    System.out.println("Big Decimal : "+bigDecimal);
}catch(NoSuchElementException error){
    System.out.println("Error please try again");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM