toFixed Reflects Binary Float Reality
See why toFixed output follows the stored binary float instead of decimal rounding, then round money amounts predictably with Number.EPSILON.
Code
// toFixed 的输出跟随数字真实的二进制表示 (binary float),不是十进制四舍五入
console.log('1.005 ->', (1.005).toFixed(2)); // 1.00:存储值略小于 1.005
console.log('2.675 ->', (2.675).toFixed(2)); // 2.67:同样落在下界
console.log('1.25 ->', (1.25).toFixed(1)); // 1.3 :二进制可精确表示,正常进位
// toPrecision(17) 能看到存储值;toFixed(20) 直接展开全部二进制含义
console.log('stored 1.005:', (1.005).toPrecision(17));
console.log('stored 2.675:', (2.675).toPrecision(17));
console.log('1.005 expanded:', (1.005).toFixed(20));
console.log('0.1+0.2 ->', (0.1 + 0.2).toFixed(2)); // 0.30:显示层掩盖了 0.30000000000000004
// 金额场景的惯用修复:加 Number.EPSILON 抵消二进制误差后再取整
const round2 = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
console.log('round2 1.005 ->', round2(1.005).toFixed(2));
console.log('round2 2.675 ->', round2(2.675).toFixed(2));Output
Captured from a sandboxed run of this snippet in the build pipeline.
1.005 -> 1.00
2.675 -> 2.67
1.25 -> 1.3
stored 1.005: 1.0049999999999999
stored 2.675: 2.6749999999999998
1.005 expanded: 1.00499999999999989342
0.1+0.2 -> 0.30
round2 1.005 -> 1.01
round2 2.675 -> 2.68Inside the snippet
toFixed Reflects Binary Float Reality keeps everything in the function round2.
Using it
The entry-point signature is const round2 = (value)
The run emits 8 labeled sections — 1.005 ->, 2.675 ->, stored 1.005:, stored 2.675:, 1.005 expanded:, 0.1+0.2 ->, round2 1.005 ->, round2 2.675 -> — one per step.
Key statements
const round2 = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
Interactive Tools for This Topic
IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `round2` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.