Possible Duplicate:
Floating point error in representation?
So I am running this code to read float string values from a a file and store the values in to an array. When the program reads in “0.333” from the file it creates a new float value but the value is converted into 0.33329999446868896! Why is this? And how can I fix this issue? The matrices are declared as follows:
this.matrix = new double[this.getRow()][this.getCol()];
this.bMatrix = new double[this.getRow()];
try {
// make sure no blank lines at the end of the file.
for (int i = 0; (strLine = reader.readLine()) != null; i++) {
System.out.println("Line from file #" + i + " " + strLine);
String[] columns = strLine.trim().split("\\s+");
for (int j = 0; j < columns.length; j++) {
if (j < (columns.length - 1)) {
//A-matrix
this.matrix[i][j] = new Float(columns[j]).floatValue();
System.out.println("Element added to A-matrix: " + columns[j]);
} else {
// B-matrix
bMatrix[i] = new Float(columns[j]).floatValue();
System.out.println("Element added to B-matrix: " + columns[j]);
}
}
}
showMatrix();
} catch (IOException | NumberFormatException e) {
reader.close();
}
}
Thanks for any assistance.
This has to do with the way floating point numbers are represented in binary. Essentially, you can’t precisely represent 0.333. The closest you can get is the number you see. If you want a shorter version for printing, use StringFormatter or something before you output your values.