使用BigDecimal转换金额
金额从前端传过来是String类型,以元为单位;在后端进行转换,在数据库中保存为Integer类型,以分为单位
1.将前端传过来的String类型的金额转换成Integer类型
IntegerToStringUtils.stringToInteger(money, 0, "100")
2.将数据库中的得到的Integer类型的金额(分)转换成String类型发给前端,保留两位小数
IntegerToStringUtils.integerToString(buyDO.getPaymentMoney(), 2, "0.01")
3.用到的工具类
1.整数转换为字符串
/**
* 将整数转换为字符串
* @param number 需要转化的数
* @param count 精度(及小数点后几位数)
* @param multiple 增加的倍数(小于1时为缩小)
* @return string
*/
public static String integerToString(Integer number,Integer count,String multiple){
String result = "";
BigDecimal b = new BigDecimal(number.toString()).multiply(new BigDecimal(multiple)).setScale(count,BigDecimal.ROUND_DOWN);
result = b.toString();
return result;
}
2.字符串转换为整数
/**
* 将字符串转换为整数
* @param number 需要转化的数
* @param count 精度(及小数点后几位数)无小数
* @param multiple 增加的倍数(小于1时为缩小)
* @return string
*/
public static Integer stringToInteger(String number,Integer count,String multiple){
Integer result = null;
BigDecimal b = new BigDecimal(number).multiply(new BigDecimal(multiple)).setScale(count,BigDecimal.ROUND_DOWN);
result = Integer.parseInt(b.toString());
return result;
}
3.用于前端乘法(保留两位小数)
/**
* 计算金额乘法
*/
@PostMapping( "/getTotalMoney")
@ResponseBody
public R getTotalMoney(String price,String count){
return R.ok().put("data",new BigDecimal(price).multiply(new BigDecimal(count)).setScale(2,BigDecimal.ROUND_DOWN).toString());
}
4.用于前端减法(保留两位小数)
/**
* 计算金额减法
*/
@PostMapping( "/getSub")
@ResponseBody
public R getSub(String num1,String num2){
return R.ok().put("data",new BigDecimal(num1).subtract(new BigDecimal(num2)).setScale(2,BigDecimal.ROUND_DOWN).toString());
}