项目中需要把浮点数转换为字符串。
1.精度小数点后4位
2.去除该数字后面没有意义的0
1230.00 => 1230
1230.10 => 1230.1
基于正则实现
/**
* 避免整数后面的 .0 <br/>
* 默认精度 小数点后4位
*/
private static String excelNumberCellFormat(double numericCellValue) {
String cellValue;
BigDecimal big = BigDecimal.valueOf(numericCellValue);
cellValue = big.setScale(4, RoundingMode.HALF_UP).toString();
// 解决1234.0 去掉后面的.0
if (!CmUtil.isBlank(cellValue)) {
cellValue = removeLastZero(cellValue);
}
return cellValue;
}
/**
* 移除小数点后没有意义的 0
*
* <pre>
* 1230.00 => 1230
* 1230.10 => 1230.1
* =====以下是不变的=====
* 123000 => 123000
* 1230.01 => 1230.01
* </pre>
*/
public static String removeLastZero(String str) {
if (!str.contains(".")) {
return str;
}
str = str.replaceAll("0+?$", "");
return str.replaceAll("[.]$", "");
}