Search code examples
javanumberformatexception

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"


I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)

First three lines of my input file:

Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360

Solution

  • Thanks for your anwsers. Eventually, it turns out that UTF-16 caused the problem. My input file was originally an excel file, then I saved it as UTF-16 txt, which caused this problem. I tried to save the input file as tab-delimited text file and it worked as expected.

    This is a weird cause of the NumberFormatException. Hope it helps others come across the same problem.