Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
当我尝试0.1 + 0.2使用我的 JavaScript 代码时,我得到了结果0.30000000000000004。我期待0.3结果。谁能告诉我为什么会这样?另外,我该如何解决这个问题以获得结果0.3?
0.1 + 0.2
0.30000000000000004
0.3
使用来自 Alnitak 的输入进行编辑
您必须使用 toFixed() 方法指定所需的小数位数。如果您只想要一位小数,请尝试
var result = (0.1 + 0.2).toFixed(1);
此表达式返回一个字符串,它表示四舍五入到小数点后 1 位的浮点数。