`toPrecision` and literals

So, I just found this:

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

Run codeHide result


Can someone please explain what exactly is going on? The only thing I can think of is that in the second case, the optimizer pre-evaluates the expression and that the optimizer's implementation toPrecision

is different from the compiler.

Tested:

  • 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: decimal point is triggered, great observation - however if we add a decimal point in number

, it won't suddenly de-expose:

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

Run codeHide result


+3


source to share


1 answer


This is an operator priority issue.

With the parentheses added, your expression looks like this:



(-1234).toPrecision(3)  // "-1.23e+3"
-(1234..toPrecision(3)) // -1230

      

1234..toPrecision(3)

first, it calculates what is "1.23e+3"

.
Then the expression becomes -"1.23e+3"

that -1230

.

+6


source







All Articles