Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.toFixed() called on negative exponential numbers returns a number, not a string

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?

like image 539
Ionică Bizău Avatar asked Apr 19 '16 14:04

Ionică Bizău


1 Answers

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

like image 124
lipp Avatar answered Sep 28 '22 17:09

lipp