views:

129

answers:

5

In JavaScript it is valid to end an integer numeric literal with a dot, like so...

x = 5.;

What's the point of having this notation? Is there any reason to put the dot at the end, and if not, why is that notation allowed in the first place?

UPDATE:

Ok guys, since you mention floats and integers... We are talking about JavaScript here. There is only one number type in JavaScript which is IEEE 754.

5 and 5. have the same value, there is no difference between those two values.

A: 

What if it wouldn't be an integer, but a floating point literal?

Jim Brissom
+1  A: 

That's a floating point number. Unlike any other language I've ever encountered, all numbers in Javascript are actually 64-bit floating numbers. Technically, there are no native integers in Javascript. See The Complete Javascript Number Reference for the full ugly story.

Asaph
Would the downvoter care to comment?
Asaph
+2  A: 

The correct answer in this case is, that it makes absolutely no difference.

Every number in JavaScript is already a 64bit floating point number.

The ". syntax" is only useful in cases where you can ommit the fixed part because it's 0:

.2 // Will end up as 0.2
-.5 // Will end up as -0.5

So overall it's just saving a byte, but it makes the code less readable at the same time.

Ivo Wetzel
It would make sense that non-integer values (values with decimal fractions) have the dot (obviously) and integer values don't. so either it is just an integer like 5 or it is a real number like 5.01 ... but why is 5. allowed? If the dot in this case does not make a difference then this notation is useless. Why whould they enable this notation then?
Šime Vidas
+4  A: 

I guess it is just compatibility with other C-like languages where the dot does matter.

KennyTM
I'd call that legacy... But yes, that's probably the reason. I guess, the creator of JavaScript just copied the notation from C, but then later decided to define only one number type (and then didn't think of revisiting the notation).
Šime Vidas
+2  A: 

You DO need the decimal point if you call a method on an integer-

5.toFixed(n)  throws an error,

but 5..toFixed(n) returns the string '5.'followed by n zeroes.

If that doesn't look right, (5).toFixed(n) will work, or 5.0.toFixed(n).
kennebec
Yea, I read that on wtfJS some time ago :) I don't want to open another question for this, so I'll just ask here: Why would you want to call methods on numeric literals?
Šime Vidas