Reputation: 673
I am reading Excel data using java apache. I got format issue while reading double value such as 869.87929 (in excel) into 869.8792899999999 (in java).
I'm using following files to read excel data.
1. Schema.csv: SheetName,2-int-Double
2. File.xls:
col1 | col2 123 | 869.87929
Sample code:
if(type.equals("Double")){
Double fval=Double.parseDouble(content[i-1]);
String sval=fval.toString();
listObjects.add(new Double(Double.parseDouble(sval)));
}
Note: type from schema.csv & content [] value from file.xls
Upvotes: 0
Views: 1441
Reputation: 533432
There is no point converting number back and forth to Strings as this shouldn't do any thing useful.
Try doing
listObjects.add(new BigDecimal(content[i-1]));
with rounding you can do
listObjects.add(new BigDecimal(content[i-1]).setScale(9, RoundingMode.HALF_UP));
though I suspect the rounding error has occurred before this point as this should do basically the same thing as
listObjects.add(new Double(content[i-1]));
with rounding you can do
double d = Double.parseDouble(content[i-1]);
double round9 = Math.round(d * 1e9) / 1e9;
listObjects.add((Double) round9);
These are much the same as the number is within the precision of double and there should be no additional error here (i.e. the error is likely to be before this point)
Upvotes: 1
Reputation: 1179
If you use Apache POI - you can use getCellType()==Cell.CELL_TYPE_NUMERIC
comparison and getNumericCellValue()
from Cell interface.
Upvotes: 1
Reputation: 647
Double is not good for preserving precision. Preffered is using BigDecimal. I believe this is your problem.
https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal
Upvotes: 1