简体   繁体   English

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

[英]Why multiply Math.round input say by 1000 and then divide result?

A function to convert from temperatures is written below 从温度转换的函数写在下面

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

My question is this line: 我的问题是这一行:

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

Why the need to multiply by 1000? 为什么需要乘以1000? and also divide result by 1000? 再将结果除以1000?

Multiplying by 1000 moves the decimal point 3 digits to the right. 乘以1000将小数点向右移动3位数字。 5.333333 = > 5333.333 5.333333 => 5333.333

Rounding rounds to whole integers. 四舍五入为整数。 (Only zeros after decimal point) 5333.333 = > 5333.000 (小数点后仅零)5333.333 => 5333.000

After that dividing by 1000 moves the decimal point back to where it started. 之后,除以1000,将小数点移回到起点。 5333.000 = > 5.333000 5333.000 => 5.333000

The result is, that the number is rounded to 3 digits after the decimal point. 结果是,数字四舍五入到小数点后的3位数字。 5.333333 = > 5.333000 5.333333 => 5.333000

Is to round up the output to 3 decimals: 是将output舍入到三位小数:

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM