1

I am having difficulties reading string number values from a .csv file and converting them into double values. Here is the code:

String filename = "/home/mahmoud/Desktop/CSV/remake1.csv";

    BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
    int val;

try {

    br = new BufferedReader(new FileReader(filename));
    while ((line = br.readLine()) != null) {

            // use comma as separator
        String[] country = line.split(cvsSplitBy);

        val = Integer.parseInt(country[4]);

                    System.out.println(val);

    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

System.out.println("Done");
}

When I compile the program I get the following error "Exception in thread "main" java.lang.NumberFormatException: For input string: "6.55"

Here is the content of the .csv file:

2012-12-03,5.63,6.57,5.32,6.55,5816300,6.55

2012-11-01,4.66,5.68,4.37,5.59,5752000,5.59

2012-10-01,5.27,5.40,4.42,4.67,5958000,4.67

2012-09-04,5.91,6.56,5.21,5.26,5930600,5.26

any suggestion on how to fix that problem? Thank You

5
  • 2
    If it's a float, why are you using Integer.parseInt()? Declare float val;, and use Float.parseFloat() instead. Commented Mar 13, 2014 at 21:50
  • 1
    Or better, Double.parseDouble() Commented Mar 13, 2014 at 21:55
  • True, but given the numbers in the example, I figured a float would be sufficient. Commented Mar 13, 2014 at 21:58
  • The question says "converting them into double values". Commented Mar 13, 2014 at 22:17
  • You are only handling a subset of the CSV file syntax. Your code will break if there are ever double-quote delimited strings with commas in them. You probably don't need to care about this since you only need to handle one very specific CSV file, but using a library like Apache Commons CSV, Open CSV, or Super CSV would avoid such issues. Commented Mar 13, 2014 at 22:22

2 Answers 2

3

The number format shows that it's not an integer, but a double.

So you should declare val as a double:

double val;

And use the following line to parse :

val = Double.parseDouble(country[4]);
Sign up to request clarification or add additional context in comments.

2 Comments

The question says "converting them into double values", not float.
Edited to double. Thx.
1

Your title says you want double, yet you parse your String using Integer.parseInt(), which will parse Integers. Use Double.parseDouble() instead to get a double value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.