首页 > 解决方案 > 为什么将 Math.round 输入乘以 1000 然后除以结果?

问题描述

从温度转换的函数写在下面

function tryConvert(temperature, convert /*callback*/) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

我的问题是这一行:

  const rounded = Math.round(output * 1000) / 1000;

为什么需要乘以 1000?并将结果除以 1000?

标签: javascript

解决方案


乘以 1000 将小数点向右移动 3 位。5.333333 = > 5333.333

四舍五入到整数。(小数点后只有零)5333.333 = > 5333.000

之后除以 1000 将小数点移回它的开始位置。5333.000 = > 5.333000

结果是,该数字被四舍五入到小数点后 3 位。5.333333 = > 5.333000


推荐阅读