Vue 数字相加、相减精度丢失处理。
•
前端
方法 一:
// num 是数值,decimals是精度几位
function round(num, decimals) {
const factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
}
const a = 0.1;
const b = 0.2;
console.log(round(a + b, 1)); // 0.3
方法 二:
//可以传你要的小数几位 let num = 2 const a = 0.1; const b = 0.2; console.log((a+b).toFixed(num)); // 0.30
方法 三:扩大运算范围:将浮点数转化为整数,相乘或相加后再除回去,可以避免小数位精度的影响。
let num1 = 0.1; let num2 = 0.2; let sum = (num1 * 10 + num2 * 10) / 10; console.log(sum); // 0.3
最后就是使用第三方库:例如 decimal.js、big.js 等第三方库可以提供更高精度的浮点数运算。
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/314d285cf6.html
