I'm reading data from CSV file. One of the fields contains the value 1,167.40
. The code piece for reading this field is the following:
String csvFilename = "TEST_FILE.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
while((row = csvReader.readNext()) != null)
{
double val = Double.parseDouble(row[0]); // !!!
}
csvReader.close();
The line double val = Double.parseDouble(row[0])
results in the following error message:
java.lang.NumberFormatException: For input string: "1,167.40"
How to solve this issue?
P.S. For other values like 111.64
this error does not appear.
The error is in the comma ,
in the middle of your input. A quick dirty solution would be removing it before parsing it as a double
.
double val = Double.parseDouble(row[0].replaceAll(",", ""));
The better solution is using a NumberFormat
to handle this:
//assumes your server already has English as locale
NumberFormat nf = NumberFormat.getInstance(); /
//...
double val = nf.parse(row).doubleValue();