2017-02-10 93 views
0

請在下面找到代碼片段。該實現讀取Excel表格中特定列的單元格值。excel中的數值單元格值在小數點後附加額外數字時被異常讀取

諸如459000.00之類的數值正在被代碼讀取爲459000.00000000006。對於少數人來說,它工作得很好,但對一些人來說卻是失敗的。

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(); 
       } 

回答

1

Excel的結果比Java更圓整。存儲的真正價值可能是459000.00000000006,但顯示爲459000.0

如果我輸入459000.00000000006到Excel會顯示459000

一個簡單的解決方案是使用你的名字有點圓。

例如回合到6位小數

/** 
* Performs a round which is accurate to within 1 ulp. i.e. 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

相關問題