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 isundefined
,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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With