2017-06-14 55 views
0

我有这样的代码:错误解析双java的

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"); 
    } 

这是我的输出:

金属阅读:47.386.578

金属没有点:47386578

转换金属: 4.7386578E7

问题是,为什么我的转换结束时会出现“E7”金属? 在此先感谢。

+0

假设你参考这个[文章](https://stackoverflow.com/questions/6171823/how-can-i-change-2-5e7-to-a-normally-formatted-number)。 –

+0

双精度不具有无限精度。这是你在科学记数法中的价值。 –

+0

这会给你很多关于“为什么”问题的背景:https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency –

回答

2

“Ex”其中“x”是数字,表示指数。所以在你的情况下,数字“4.7386578E7”将是“47386578”。只要把点7个地方。

不过,如果你想与没有指数形式打印号码,就可以在最后印刷使用的“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意味着要打印没有小数部分的浮点值。

我希望这个答案能帮助你。

0

代替原始double或float使用“java.math”包中的“BigDecimal”。这会给你更精确的输出。请参阅下面使用的代码段。

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"); 
}