Convert String to double in Java

Asked

Viewed 1,344 times

1

I am reading data from an external file with CSV format. However this data is coming in CSV format String. There is a price field that I need to turn into double for handling purposes.

Class Catalogs

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


public class Catalog {

private ArrayList<Product> products = new ArrayList<Product>();

public ArrayList<Product> getProducts() {
    return products;
}

public void setProducts(Product p) {
    products.add(p);
}


public ArrayList<Product> showProducts(){
    for(Product prod : products){
        System.out.println("id:"+ prod.getId());
        System.out.println("Price:"+ prod.getPrice());
    }

    return getProducts();
}
public static void main(String[] args){
    File file = new File("C:\\Users\\casa\\Desktop\\catalog.csv");
    String line = new String();
    Product p = new Product();
    Catalog c = new Catalog();

    try {
        Scanner reader = new Scanner(file);
        while(reader.hasNext()){
            line = reader.nextLine();

            String[] value = line.split(",");

            p.setId(value[0]);
            p.setPrice(value[1]);

            c.setProducts(p);

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    c.showProducts();
}

}

Class Products

public class Product {
private String id;
private double price;
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}
public double getPrice() {
    return price;
}
public void setPrice(String p) {
    double price = Double.parseDouble(p);
    this.price = price;
}
}

I tried to use the method parseDouble()to transform the attribute when set by the method setPrice, but the following error occurred:

Exception in thread "main" java.lang.NumberFormatException: For input 
string: ""price""
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Product.setPrice(Product.java:16)
at Catalog.main(Catalog.java:41)

3 answers

5


The function is correct. You can use both Double.parseDouble, how much Double.valueOf, but both methods will return the exception Numberformatexception case to string is invalid, for example, using comma instead of floating point.

For example:

┌─────────────────────────────┬──────────┐
│ Double.valueOf("2");        │ Válido   │
├─────────────────────────────┼──────────┤
│ Double.valueOf("2.5");      │ Válido   │
├─────────────────────────────┼──────────┤
│ Double.valueOf("2.59");     │ Válido   │
├─────────────────────────────┼──────────┤
│ Double.valueOf("2.599");    │ Válido   │
├─────────────────────────────┼──────────┤
│ Double.valueOf("2,599");    │ Inválido │
├─────────────────────────────┼──────────┤
│ Double.valueOf("2.599,00"); │ Inválido │
├─────────────────────────────┼──────────┤
│ Double.valueOf("259:900");  │ Inválido │
├─────────────────────────────┼──────────┤
│ Double.valueOf("R$259");    │ Inválido │
└─────────────────────────────┴──────────┘

The table also applies to the Double.parseDouble method()

If you have invalid characters in your string, it is necessary to treat it before trying to convert to double. For this you can use Regex or a simple String.replace, for example:

String preco1 = "2,599"
    .replace("(?:[^\\d\\,])", "") //Remove todos os caracteres não numerais e nem a vírgula
    .replace(",", "");            // Substitui a vírgula pelo ponto

String preco2 = "2.599,12"
    .replace("(?:[^\\d\\,])", "")
    .replace(",", "");

System.out.println( Double.valueOf(preco1) );
System.out.println( Double.valueOf(preco2) );

In your case, you are trying to convert the value "price", and since this is not a numerical value (with or without floating point), the algorithm cannot convert it.

  • The format of the data in the file is like this: "4357590126397428","R$ 629.99", the first column being id and the second is price. I couldn’t use the method replaceto remove characters (including quotes are coming together).

1

Let’s get into the trouble of this code:

  • The product should not receive a price as String by default. You may even have an auxiliary method that does this as convenience, it is questionable whether you should be in the class Product, but can be done as something extra.
  • Don’t use a price like double, this type is not accurate. Use a BigDecimal.
  • The capture of the exception in Catalog does nothing useful, so remove it.
  • You add a product to the catalog and no arrow products in it. It sounds silly, but if misconcepting one thing wrong, it will conceptualize several other things. And it makes the code less intuitive.
  • The Main() should not be in this class.
  • That one split() It’s pretty slick, but I won’t touch it.
  • Usually what interacts with the user is also usually out, so showProducts() should be in another class, and maybe have another name. And it is strange and shows and return the products.
  • If you are going to register a new product, create a new product, what you have done will not produce the result you expect.
  • Your main problem is being able to validate data entry. In another language I would adopt a different strategy, But Java culture is about exceptions. Do not try to fix the data, this is risky, if the person typed wrong show her that this is happening and teach her to do it right, besides being a better usability the risk of something going wrong is less.

Sort of like this:

while (reader.hasNext()) {
    String line = reader.nextLine();
    String[] value = line.split(",");
    Product p = new Product();
    p.setId(value[0]);
    try {
        p.setPrice(value[1]);
    } catch (NumberFormatException e) {
        System.out.println("valor digitado não é válido, tente novamente");
        continue;
    }
    c.addProduct(p);
}

private BigDecimal price;
public void setPrice(String p) {
    this.price = new BigDecimal(p);
}

I put in the Github for future reference.

0

I got it solved! I added this line of code line = line.replaceAll("[\"R$ ]", ""); right after reading a line from the file to remove all the special characters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.