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 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.
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.
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.
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(',' , '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With