`toPrecision` and literals

Viewed 54

So I just found this:

let number = -1234;
console.log(number.toPrecision(3)); // -1.23e+3
console.log(-1234..toPrecision(3)); // -1230

Can anyone explain what exactly is going on? The only thing I can think of is that in the second case the optimiser pre-calculates the expression, and that the optimiser's implementation of toPrecision is different from the compiler's.

Tested on:

  • Safari/Mac, Version 10.1 (12603.1.30.0.34)
  • Chrome/Mac, Version 59.0.3071.104 (Official Build) (64-bit)
  • Firefox/Mac, 54.0.1 (64-bit)

EDIT: Re: being triggered by the decimal point, great observation - however, if we add the decimal point into number, it doesn't suddenly de-exponentise:

let number = -1234.5;
console.log(number.toPrecision(3));  // -1.23e+3
console.log(-1234.5.toPrecision(3)); // -1230

1 Answers
Related