请在下面找到代码片段。该实现读取 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();
}
最佳答案
Excel 比 Java 对结果进行更多舍入。存储的真实值可能是 459000.00000000006,但显示为 459000.0
如果我在 Excel 中输入 459000.00000000006
,它会显示 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;
}
关于java - excel中的数字单元格值读取异常,小数点后附加额外数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158233/