Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 1 and 1.0 [duplicate]

Tags:

javascript

Recently I found out that this is completely valid:

1..toString();  //"1"

To me it looks a little bit weird in the first place, but with further explorations I figured out that it works is because the browser treats the first 1. as a number.

This leads us to the question. If I call .toString on a number:

1.toString();  //SyntaxError

it won't work. However, if I do:

1.0.toString(); /*or*/ 1..toString();  //"1"

it works.

Why is there a difference between 1 and 1.0? I thought there is no number types in JavaScript? Why would the decimal point matter?

like image 551
Derek 朕會功夫 Avatar asked Feb 24 '14 09:02

Derek 朕會功夫


People also ask

What is the difference between 1.0 and 1?

Put simply, 1 is an integer, 1.0 is a float.

What does 1.0 mean in math?

Helpful (0) There is no difference both (1.0 or 1.) are same in mathematics. Both are real numbers with same magnitude.

What is the difference between 01 and 1?

There is no difference between the numbers 01 and 1 . They are absolutely identical.

Is float a double?

Difference in Precision (Accuracy) float and double both have varying capacities when it comes to the number of decimal digits they can hold. float can hold up to 7 decimal digits accurately while double can hold up to 15.


2 Answers

You get the syntax error because 1.toString() is trying to call toString() on a floating point value but without using the dot access operator.

Whatever is interpreting that '.' has to decide whether it is there as a floating point indication or the access operator. Vagueties are not good, so one of those possibilities takes precedence. And in JavaScript's case, the floating point indicator is taking precedence (as described by peteykun in their answer, the lexer determines which code characters are considered part a number).

1..toString() and 1.0.toString() work because the floating point is already there so there is no uncertainty. We know then, that the second '.' has to be the access operator.

like image 63
Rudi Kershaw Avatar answered Sep 25 '22 15:09

Rudi Kershaw


It does not have much to do with the type of 1 or 1.0 but with the way lexer parses your code. A period following a string of digits is treated as a decimal point and not as the class member access (.) operator.

Enclosing 1 in parentheses solves the problem:

(1).toString();
like image 23
peteykun Avatar answered Sep 25 '22 15:09

peteykun