首页 > 其他 > 详细

POI读入Excel用String读取数值类型失真问题(精度丢失)

时间:2019-09-05 14:51:21      阅读:476      评论:0      收藏:0      [点我收藏+]

问题:POI读取Excel数值单元格时,读取的小数数值与真实值不一致

话不多说,直接上代码!

public static String getRealStringValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}else {
final CellType cellType = cell.getCellType();
if (CellType.NUMERIC.equals(cellType)) {
cellValue = DoubleUtils.realStringValueOfDouble(cell.getNumericCellValue());
} else {
cell.setCellType(CellType.STRING);
cellValue = cell.getStringCellValue();
}
return cellValue;
}
}

public class DoubleUtils {

private DoubleUtils() {
}

public static String realStringValueOfDouble(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.parseInt(doubleStr.substring(indexOfE + BigInteger.ONE.intValue()));
int xsLen = xs.toByteArray().length;
int scale = xsLen - pow > 0 ? xsLen - pow : 0;
final String format = "%." + scale + "f";
doubleStr = String.format(format, 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;
}
}



POI读入Excel用String读取数值类型失真问题(精度丢失)

原文:https://www.cnblogs.com/shipc/p/shipc.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!