货币计算避免用 Float 或 Double, 会丢失精度. 建议用 BigDecimal
使用场景
最近在做小程序支付功能, 微信提供的统一下单接口金额单位为分, 于是需要将金额从元转为分
最开始使用 Float 进行计算
- public static void main(String[] args) {
- //0.01 元
- String fee = "0.01";
- // 转为 1 分
- int money = (int)(Float.parseFloat(fee)*100);
- System.out.println(money);
- }
0.01 元是没有问题的, 换了一个较大的金额 "9999999", 结果计算出来的值为 9999998.72
于是改用 BigDecimal
- public static void main(String[] args) {
- // 金额, 单位元
- String fee = "9999999";
- BigDecimal decimal1 = new BigDecimal(fee);
- BigDecimal decimal2= new BigDecimal(100);
- // 金额, 单位转为分
- int money = decimal1.multiply(decimal2).intValue();
- System.out.println(money); //9999999
- }
来源: http://www.bubuko.com/infodetail-3219410.html