一、在使用Java中使用double做为单价计算金额的时候会出现精度丢失的问题。
解决办法 : 使用大数据运算类 ---> BigDecimal类。具体看下面代码
//计算金额 //转型防止丢失精度
BigDecimal bigDecimalPrice = new BigDecimal(String.valueOf(goods_price));
BigDecimal bigDecimalTotal = new BigDecimal(goods_total);
double bigDecimalMoney = bigDecimalPrice.multiply(bigDecimalTotal);
double goods_newMoney = bigDecimalMoney.doubleValue();
解析 :
1. BigDecimal bigDecimalPrice = new BigDecimal(String.valueOf(goods_price));
创建对象,将单价传递进去,但是double类型的参数虽然使用了BigDecimal类仍然可能会造成精度丢失。解决办法就是将传递的double类型的goods_price使用String.valueOf( )方法转换为String。
这个传递String类型的构造参数就不会造成精度丢失。
2. BigDecimal bigDecimalTotal = new BigDecimal(goods_total);
这个传递的是int类型的参数,不需要转型,因为不会造成精度丢失。
3. 使用multiply(BigDecimal)方法将单价与数量相乘,大数据的四则运算全是使用方法的形式。具体方法自行查找API。
4. 最后使用doubleValue( )方法将最终计算出来的金额转换为double类型即可。
简写为一行 :
double goods_Newmoney = new BigDecimal(String.valueOf(goods_price)).multiply(new BigDecimal(goods_total)).doubleValue();
对于循环求累加思路 : 使用循环并使用add( )方法 (加) 示例如下 :
BigDecimal number01 = new BigDecimal("0");
for (int i = 0; i < 5; i++) {
BigDecimal number02 = new BigDecimal("6.6");
number01 = total.add(number02);
}
System.out.println(number01);
二、在JavaScript中浮点数累加计算精度丢失问题。代码如下 :
通用JS方法 : 复制使用即可。
//num1 num2传入两个值 symbol +-*/符号
function amend(num1,num2,symbol){
var str1=num1.toString(),str2=num2.toString(),result,str1Length,str2Length
//解决整数没有小数点方法
try {str1Length= str1.split('.')[1].length} catch (error) {str1Length=0}
try {str2Length= str2.split('.')[1].length} catch (error) {str2Length=0}
var step=Math.pow(10,Math.max(str1Length,str2Length))
//
console.log(step);
switch (symbol) {
case "+":
result= (num1*step+num2*step)/step
break;
case "-":
result= (num1*step-num2*step)/step
break;
case "*":
result= ((num1*step)*(num2*step)) / step/step
break;
case "/":
result= (num1*step)/(num2*step)
break;
default:
break;
}
return result
}
解析 : 参数1 、参数2为计算的两个数,参数3为运算符 +、-、*、/ 。具体使用根据情况而定。
例如循环累加 :
//定义总金额
let totalMoney = 0;
for (let i = 0;i<info.list.length;i++){
totalMoney = amend(totalMoney,info.list[i].goods_money,"+");
}
//给其总金额赋值
vm.ckd_money = totalMoney;