0

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

Metal without dots: 47386578

Converted Metal: 4.7386578E7

the question is, why do I have that "E7" at the end of my converted metal? Thanks in advance.

Davide Melis
  • 39
  • 1
  • 8

2 Answers2

2

the "Ex" where "x" is a number, means Exponential. So in your case, the number "4.7386578E7" will be "47386578". Just take right the dot 7 places.

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:

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.

I hope this answer helps you.

0

Instead of primitive double or float use "BigDecimal" of "java.math" package. 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");
}
Bhanu Boppana
  • 134
  • 1
  • 2
  • 10