Šime Vidas
Šime Vidas

Reputation: 185973

Why is an integer literal followed by a dot a valid numeric literal in JavaScript?

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.

Upvotes: 9

Views: 1442

Answers (5)

kennebec
kennebec

Reputation: 104810

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

5.toFixed(n) // throws an error

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

If that doesn't look right, (5).toFixed(n), or 5.0.toFixed(n), will work, too.

Upvotes: 2

kennytm
kennytm

Reputation: 523514

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

Upvotes: 4

Ivo Wetzel
Ivo Wetzel

Reputation: 46756

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.

Upvotes: 1

Asaph
Asaph

Reputation: 162831

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.

Upvotes: 1

Jim Brissom
Jim Brissom

Reputation: 32959

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

Upvotes: -1

Related Questions