JavaScript中Decimal乘法异常:为何1000.56*10结果不符?
Why does
1000.56 * 10 return 10005.59999999999 instead of 10005.6 in JavaScript? Great question! This unexpected result boils down to how JavaScript represents and calculates with floating-point numbers. Let’s break it down clearly:
- JavaScript uses the IEEE 754 double-precision floating-point standard for all numeric values. This system stores numbers as binary fractions, not the decimal fractions we’re used to working with.
- The core issue is that some decimal fractions can’t be represented exactly as binary fractions. For example,
0.56in decimal translates to an infinite repeating binary fraction (similar to how1/3is0.333...in decimal). When you write1000.56in your code, JavaScript doesn’t store the exact value—it stores a close binary approximation. - When you multiply this approximated value by 10, the tiny inherent error in the original number gets magnified, resulting in the seemingly wrong output
10005.59999999999instead of the precise10005.6. - The reason
100.56 * 10works as expected is just a coincidence of how the binary approximation for that specific number lines up; the underlying limitation of floating-point representation still applies here—it just doesn’t produce a visible error.
If you need to avoid this kind of precision issue (especially for use cases like currency calculations), here are a few common workarounds:
- Use integer arithmetic: Multiply values by a power of 10 (like 100 for cents) to work with whole numbers, then divide back when you need to display the result.
- Use
toFixed()to round the result to a specified number of decimal places (note: this returns a string, so you’ll need to convert it back to a number if needed). - Use dedicated libraries for precise decimal arithmetic (these are widely available for JavaScript).
To see the binary approximation of
0.56for yourself, run this code:console.log(0.56.toString(2)); // Outputs a long, repeating binary fraction
内容的提问来源于stack exchange,提问作者Manish Parab
相关产品推荐
相关产品推荐

