javascript - 为什么下面的舍入函数不对某些数值进行舍入?

标签 javascript math

<分区>

这是函数:

export const round = (value, precision) => {
  const multiplier = Math.pow(10, precision || 0)
  return Math.round(value * multiplier) / multiplier
}

当我在此函数中使用 round 时:

SET_CAMERA_ZOOM (state, number = 0) {
  // the default is 1.4
  const cameraZoom = state.markerEditor.cameraZoom
  const roundedCameraZoom = round(cameraZoom, 1)
  state.markerEditor.cameraZoom = roundedCameraZoom + number
}

当数字为 0.4 时我得到:

1.4
1.7999999999999998
1.8
2.2
2.6
3

当数字为 -0.4(从 3 开始)时:

2.6
2.2
1.8000000000000003
1.8
1.4
0.9999999999999999

为什么我得到这些未舍入的数字以及如何修改 round 以便我得到 1.81

更新:我尝试了来自其他链接的解决方案。就像这个:

precision = precision || 0
return parseFloat(parseFloat(number).toFixed(precision))

我仍然得到像这样的东西:0.9999999999999999

最佳答案

你得到像 1.7999999999999998 这样的数字的原因是因为 javascript 数字的精度有限(参见 Is floating point math broken? )

所以当你用分数做事情时,你会得到如下结果:

function round (value, precision) {
  var multiplier = Math.pow(10, precision || 0);
  return Math.round(value * multiplier) / multiplier
}

for (var i=1, x=-.4; i<5; i++) console.log(round(x*i, 1) + 1);

四舍五入有效,但是一旦您进行更多运算(即 + 1),您就会回到精度有限的问题上。

最好将 toFixed 作为最后一步应用,这样您就可以在操作过程中保持精度,并且在保持舍入的同时只会在最后丢失它,例如

// Do arithmetic, then round as very last operation
for (var i=1, x=-.4; i<5; i++) console.log(Number((x * i + 1).toFixed(1)));

Number(...) 的使用在末尾转换为数字以显示精度并保留舍入。

关于javascript - 为什么下面的舍入函数不对某些数值进行舍入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333582/

相关文章:

javascript - 无法加载 c++ bson 扩展

javascript - 卸载 React.js 节点

javascript - 如何在没有后退按钮的情况下 href 到另一个 View

javascript - JS if (a == b || a == c) 的缩写

math - float 学有问题吗?

math - 两次旋转之间的误差?

javascript - 从 ember.js 中的 Controller 检索计算属性

algorithm - 当等式右侧有多个循环函数调用时,求解循环关系的方法是什么?

c - 用于比较 4 个数字的简洁代码

c# - 始终返回正值