excel中的数值单元格值会在小数点后附加额外数字的情况下exception读取

请在下面的代码片段find。 该实现读取excel表格中特定列的单元格值。

数字值(如459000.00)正在被代码读取为459000.00000000006。 对于less数人来说,这是工作得很好,但是对一些人来说却是失败的。

try { String AmountColumn="C"; File FS = new File(FileLocation); FileInputStream FileStream = new FileInputStream(FS); XSSFWorkbook FileWorkbook = new XSSFWorkbook(FileStream); Sheet FileWorksheet = FileWorkbook.getSheetAt(0); double[] AmountArray = new double[FileWorksheet.getPhysicalNumberOfRows() - 1]; Iterator<Row> iterator2 = FileWorksheet.iterator(); int i2 = 0; while (iterator2.hasNext()) { if (i2 == 0) { iterator2.next(); } else { AmountArray[i2 - 1] = iterator2.next().getCell(CellReference.convertColStringToIndex(AmountColumn)).getNumericCellValue(); System.out.println("Amount is: " + AmountArray[i2 - 1]); } i2++; } Amount = AmountArray; } catch (Exception e) { e.printStackTrace(); } 

Excel的结果比Java更圆整。 存储的真实值可能是459000.00000000006,但显示为459000.0

如果我input459000.00000000006到Excel中显示459000

一个简单的解决方法是对你得到的名字进行一点舍入。

例如舍入到小数点后6位

 /** * Performs a round which is accurate to within 1 ulp. ie for values very close to 0.5 it * might be rounded up or down. This is a pragmatic choice for performance reasons as it is * assumed you are not working on the edge of the precision of double. * * @param d value to round * @return rounded value */ public static double round6(double d) { final double factor = 1e6; return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d : (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor; } 

https://github.com/OpenHFT/Chronicle-Core/blob/master/src/main/java/net/openhft/chronicle/core/Maths.java#L121