业务点:
批量导入订单,订单中包含价格,为4.5,6.7这种格式的。
问题:
poi中需要按照字符串形式拿出来数据,映射成具体的实体类。
在cell.setCellType(Cell.CELL_TYPE_STRING) 即设置按照字符串读取时发生精度异常
例:8.2取出后就是8.19999993,而7.2则正常
因为是接盘的别人的项目,先贴出原代码:
private static String getCellStringValue(Cell cell) {
if (cell == null) {
return "";
} else {
cell.setCellType(1);
return cell.getStringCellValue().trim();
}
}
后封装方法用于解决此问题,同时解决科学计数法读取的问题:
private static String getCellStringValue(Cell cell) {
if (cell == null) {
return "";
} else {
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
return getRealStringValueOfDouble(cell.getNumericCellValue());
}
cell.setCellType(1);
return cell.getStringCellValue().trim();
}
}
private static String getRealStringValueOfDouble(Double d) {
String doubleStr = d.toString();
boolean b = doubleStr.contains("E");
int indexOfPoint = doubleStr.indexOf('.');
if (b) {
int indexOfE = doubleStr.indexOf('E');
BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
+ BigInteger.ONE.intValue(), indexOfE));
int pow = Integer.valueOf(doubleStr.substring(indexOfE
+ BigInteger.ONE.intValue()));
int xsLen = xs.toByteArray().length;
int scale = xsLen - pow > 0 ? xsLen - pow : 0;
doubleStr = String.format("%." + scale + "f", d);
} else {
java.util.regex.Pattern p = Pattern.compile(".0$");
java.util.regex.Matcher m = p.matcher(doubleStr);
if (m.find()) {
doubleStr = doubleStr.replace(".0", "");
}
}
return doubleStr;
}
希望对有需要的朋友有帮助!