admin管理员组

文章数量:1356741

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?

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?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Apr 19, 2016 at 14:55 Ionică BizăuIonică Bizău 114k94 gold badges310 silver badges487 bronze badges 3
  • It's parsed as -(3e5.toFixed()) – Bergi Commented Apr 19, 2016 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 Commented Apr 19, 2016 at 15:05
  • 1 @T.J.Crowder Definitely, I was just curious what was going on. :-) – Ionică Bizău Commented Apr 19, 2016 at 16:14
Add a ment  | 

2 Answers 2

Reset to default 6

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

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

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.

本文标签: