为什么要将 Math.round 输入乘以 1000,然后除以结果?

1 javascript

下面写了一个从温度转换的函数

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();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是这一行:

  const rounded = Math.round(output * 1000) / 1000;
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*tel 5

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

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

除以 1000 后,小数点会移回原来的位置。5333.000 = > 5.333000

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