开发者

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.


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


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜