You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.56 in decimal translates to an infinite repeating binary fraction (similar to how 1/3 is 0.333... in decimal). When you write 1000.56 in 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.59999999999 instead of the precise 10005.6.
  • The reason 100.56 * 10 works 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.56 for yourself, run this code:

console.log(0.56.toString(2)); // Outputs a long, repeating binary fraction

内容的提问来源于stack exchange,提问作者Manish Parab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:10:51