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

时间:2018-05-25 11:14:00

标签: 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();
}

我的问题是这一行:

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

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

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

output向上舍入为3位小数:

示例:

const rounded = Math.round(1.23456 * 1000) / 1000; // = 1.235
console.log(rounded);

相关问题