Why does 0.-5 evaluate to -5?

JavascriptNumbers

Javascript Problem Overview


Suppose I write 0.5 as 0.-5 in unexpected way, but it can still run. What does 0. in 0.-5 do so that it can still run and evaluates to -5?

I also tried alert(0.-5+1) which prints -4, does JavaScript ignore 0. in 0.-5?

Javascript Solutions


Solution 1 - Javascript

Trailing digits after a . are optional:

console.log(0. === 0); // true

So

0.-5

evalutes to

0 - 5

which is just -5. Similarly,

0.-5+1

is

0 - 5 + 1

which is

-5 + 1

or -4.

Solution 2 - Javascript

0.-5 could be successfully parsed as 0.[1], - and 5. Below is the abstract syntax tree for the expression generated by AST explorer:

Parse tree generated by AST explorer

This (in an unexpected way) is valid JavaScript and evaluates to -5.


[1] According to the grammar for numeric literals the decimal digits and exponent parts are optional:

> NumericLiteral ::
>   DecimalLiteral
>   [...]
> > DecimalLiteral ::
>   DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt

Solution 3 - Javascript

In JS you can express a number with optional decimal point.

x = 5.;    //5
x = 5. + 6.   //11

And as of Tvde1's comment, any Number method can be applied too.

5..toString()

This syntax let us run the Number functions without parentheses.

5.toString() //error
(5).toString() //good
5..toString() //good
5 .toString() // awesome

See this question to find out why.

Solution 4 - Javascript

I would think that the real answer is not about the decimal point, but is about the minus sign: isn't that going to be interpreted as an operator if it is preceded by anything that looks like a number?

Solution 5 - Javascript

console.log(0. - 5)      // -5
console.log(0 - 5)       // -5
console.log('0.' - 5)    // -5
console.log('0' - 5)     // -5
console.log(0.-5 === -5) // true

'0.' or '0' is the same in JavaScript because the type is unique for numbers, called Number. The minus operator is between Numbers, try always to convert what you pass to a Number. In Python is different first is a Float and the second an Integer because it has several types.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionocomfdView Question on Stackoverflow
Solution 1 - JavascriptCertainPerformanceView Answer on Stackoverflow
Solution 2 - JavascriptSalman AView Answer on Stackoverflow
Solution 3 - JavascriptCharlieView Answer on Stackoverflow
Solution 4 - JavascriptSean_999View Answer on Stackoverflow
Solution 5 - JavascriptΚωλζαρView Answer on Stackoverflow