Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integers in JavaScript

I'm a beginner to Javascript so forgive me if I sound dumb because I learned some Javascript from W3Fools (which are really difficult tutorials - they don't explain anything I want to know, but everything I probably can guess from my experience with C++).

I may be switching over to MDN, but if you can recommend any other tutorials, that be great.

Anyways, so here's my question:

I just read a few lines of this, and apparently:

Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec. This has some interesting consequences. There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java.

I've already seen that there are few of the data types (for variables) I'm used to from C++. But I didn't expect all numbers to automatically be floats. Isn't there any way to use integers, not float? Will a future version of JavaScript support ints?

like image 405
Mateen Ulhaq Avatar asked Jan 16 '11 04:01

Mateen Ulhaq


People also ask

What is integer type in JavaScript?

"There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java."

How are integers represented in JavaScript?

JavaScript has only floating-point numbers. Integers appear internally in two ways. First, most JavaScript engines store a small enough number without a decimal fraction as an integer (with, for example, 31 bits) and maintain that representation as long as possible.

What is number () in JavaScript?

Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25 . The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

Is integer a class in JavaScript?

You are looking for Number, not Integer , there is no Integer class in javascript.


2 Answers

There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.

Firefox 4 will have support for Typed Arrays, where you can have arrays of real ints and such: https://developer.mozilla.org/en/JavaScript_typed_arrays

Until then, there are hackish ways to store integer arrays as strings, and plucking out each integers using charCodeAt().

like image 79
erjiang Avatar answered Nov 09 '22 23:11

erjiang


I don't think it ever will support integers. It isn't a problem as every unsigned 32 bit integer can be accurately represented as a 64 bit floating point number.

Modern JavaScript engines could be smart enough to generate special code when the numbers are integer (with safeguard checks to make sure of it), but I'm not sure.

like image 42
Axel Gneiting Avatar answered Nov 10 '22 01:11

Axel Gneiting