Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NumberFormatException: For input string: "1,167.40" [duplicate]

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.

like image 795
Klausos Klausos Avatar asked Sep 12 '13 07:09

Klausos Klausos


People also ask

How do you overcome NumberFormatException?

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps: Surround the statements that can throw an NumberFormatException in try-catch blocks. Catch the NumberFormatException. Depending on the requirements of the application, take necessary action.

Is NumberFormatException a runtime exception?

The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java.

Is null NumberFormatException?

NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer. parseInt() which convert String to int, Double.


1 Answers

Double.parseDouble() does not like , in the strings you provide as parameter. Have you tried removing the , from the input? I assume 1,167.40 is the same as 1167.40.

You can try:

double val = Double.parseDouble(row[0].replace(',' , '');
like image 72
Mateusz Andrzejewski Avatar answered Oct 21 '22 13:10

Mateusz Andrzejewski