5

I noticed that when calling toFixed against a negative exponential number, the result is a number, not a string.

First, let's take a look at specs.

Number.prototype.toFixed (fractionDigits)

Return a String containing this Number value represented in decimal fixed-point notation with fractionDigits digits after the decimal point. If fractionDigits is undefined, 0 is assumed.

What actually happens is (tested in Chrome, Firefox, Node.js):

> -3e5.toFixed()
-300000

So, the returned value is -3e5. Also, notice this is not a string. It is a number:

> x = -3e5.toFixed()
-300000
> typeof x
'number'

If I wrap the input in parentheses it works as expected:

> x = (-3e5).toFixed()
'-300000'
> typeof x
'string'

Why is this happening? What is the explanation?

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • It's parsed as `-(3e5.toFixed())` – Bergi Apr 19 '16 at 15:05
  • Moral of the story: Calling methods on literal numbers is fraught with peril. For instance, `5.toFixed()` is a syntax error. Use parens or variables to avoid falling into pitfalls. (You can do the `5.toFixed()` thing with `5..toFixed()` but...just don't. Parens are nice and reliable: `(5).toFixed()`.) – T.J. Crowder Apr 19 '16 at 15:05
  • 1
    @T.J.Crowder Definitely, I was just curious what was going on. :-) – Ionică Bizău Apr 19 '16 at 16:14

2 Answers2

6

I guess this is because of higher precedence of the member ('.') operator compared to the sign operator.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

lipp
  • 5,586
  • 1
  • 21
  • 32
5

What is happening here is the order of operations. Lets break it down:

First what's going to to happen is 3e5 is going to return a number (300000), then toFixed will be called on in, turning it into a string, then the sign operator is going to be executed, coercing the string back to a number.

  • it's right, however, there is no the conception of `the sign operator` in javascript. The finally step is that **the Unary negation operator** attempts to convert its operand into a number in the process of evaluation. u can see [Unary_negation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation_(-)) – Ye Shiqing Aug 22 '17 at 23:50