1. 使用 toFixed() 方法
toFixed()是 JavaScript 内置的 Number 对象方法,它会根据指定的小数位数返回一个字符串。这个方法在输出时对结果进行了四舍五入,因此它并不总是能保证数学上的精确性,但它对于展示目的来说通常是足够的。
let num = 0.1 + 0.2; console.log(Number(num.toFixed(2))); // 输出: 0.3
2. 使用 Math.round(), Math.floor(), 和 Math.ceil()
function roundToDecimal(num, decimals) { const factor = Math.pow(10, decimals); return Math.round(num * factor) / factor;
} console.log(roundToDecimal(0.1 + 0.2, 1)); // 输出: 0.3
3. 使用整数运算
let a = 0.1 * 10; // 放大 let b = 0.2 * 10; console.log((a + b) / 10); // 缩小回原大小,输出: 0.3
4. 使用第三方库
当你的应用需要处理非常高的精度或者复杂的小数运算时,考虑使用专门设计来处理高精度数学运算的库。decimal.js 和 big.js 是两个流行的选项。它们允许你创建对象来表示数字,并提供多种运算方法以确保精度。
decimal.js
const Decimal = require('decimal.js'); // 如果是在Node.js环境中 //
在浏览器中可以直接引入 <script src="https://cdn.jsdelivr.net/npm/decimal.js/decimal.min.js"></script> let num1 = new Decimal('0.1'); let num2 = new Decimal('0.2'); console.log(num1.plus(num2).toNumber()); // 输出: 0.3
big.js
const Big = require('big.js'); // 如果是在Node.js环境中 // 在浏览器中可以直接引入 <script src="https://cdn.jsdelivr.net/npm/big.js/big.min.js"></script> let num1 = new Big('0.1'); let num2 = new Big('0.2'); console.log(num1.plus(num2).toString()); // 输出: "0.3"