JavaScript dùng IEEE 754 double-precision → lỗi chính xác (ví dụ: 0.1 + 0.2 = 0.30000000000000004).
Giải pháp
- toFixed(n) / toPrecision(n) – format hiển thị, trả về string.
- Math.round(num * 100) / 100 – làm tròn 2 chữ số.
- Integer-based: lưu tiền tệ theo cent (integer), chia 100 khi hiển thị.
- Thư viện:
decimal.js,big.js,dinero.jscho tính toán tài chính chính xác.
Ví dụ toPrecision()
<!DOCTYPE html>
<html>
<body>
<script>
var num = 28.6754;
console.log(num.toPrecision(3)); // "28.7" (3 chữ số có nghĩa)
console.log(num.toPrecision(2)); // "29"
console.log(num.toPrecision(5)); // "28.675"
</script>
</body>
</html>
Khác biệt: toFixed(n) = n chữ số sau dấu phẩy. toPrecision(n) = n chữ số có nghĩa tổng cộng.