1

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? and also divide result by 1000?

  • 5
    This rounds to three decimal places – Jared Goguen May 25 '18 at 11:14
  • @JaredGoguen Can you elaborate? I don't understand what you mean –  May 25 '18 at 11:16
  • 2
    If you have `0.12345` then it will do `Math.round(123.45 )` - > `123` then divide by `1000` -> `0.123`. The method rounds to three decimal places – Axnyff May 25 '18 at 11:17
  • 2
    More or less the same as `return convert(input).toFixed(3)` – mplungjan May 25 '18 at 11:18
  • 1
    The code *attempts* to round to three decimal places, but due to the behavior of binary floating point math the result may have non-zero decimal digits beyond the third fractional digit. – Pointy May 25 '18 at 11:21
  • Possible duplicate of [How do you round to 1 decimal place in Javascript?](https://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript) – Raymond Chen May 25 '18 at 11:24

2 Answers2

5

Multiplying by 1000 moves the decimal point 3 digits to the right. 5.333333 = > 5333.333

Rounding rounds to whole integers. (Only zeros after decimal point) 5333.333 = > 5333.000

After that dividing by 1000 moves the decimal point back to where it started. 5333.000 = > 5.333000

The result is, that the number is rounded to 3 digits after the decimal point. 5.333333 = > 5.333000

Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

Is to round up the output to 3 decimals:

Example:

const rounded = Math.round(1.23456 * 1000) / 1000; // = 1.235
console.log(rounded);
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
oma
  • 1,804
  • 12
  • 13