方法 一:
// num 是數(shù)值,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
方法 二:
//可以傳你要的小數(shù)幾位
let num = 2
const a = 0.1;
const b = 0.2;
console.log((a+b).toFixed(num)); // 0.30
方法 三:擴(kuò)大運(yùn)算范圍:將浮點(diǎn)數(shù)轉(zhuǎn)化為整數(shù),相乘或相加后再除回去,可以避免小數(shù)位精度的影響。文章來源:http://www.zghlxwxcb.cn/news/detail-594546.html
let num1 = 0.1;
let num2 = 0.2;
let sum = (num1 * 10 + num2 * 10) / 10;
console.log(sum); // 0.3
最后就是使用第三方庫:例如 decimal.js、big.js 等第三方庫可以提供更高精度的浮點(diǎn)數(shù)運(yùn)算。文章來源地址http://www.zghlxwxcb.cn/news/detail-594546.html
到了這里,關(guān)于Vue 數(shù)字相加、相減精度丟失處理。的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!