17

MDN states:

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.

This suggests all numbers are floats. Is there any way to use integers, not float?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135

5 Answers5

16

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().

erjiang
  • 44,417
  • 10
  • 64
  • 100
4

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.

Thanatos
  • 42,585
  • 14
  • 91
  • 146
Axel Gneiting
  • 5,293
  • 25
  • 30
  • 3
    All JS engines (SpiderMonkey's has from its very first implementation — the first JS engine) have used int32-maths when possible. – gsnedders Jan 16 '11 at 14:27
  • 5
    It isn't a problem... until you want a 64-bit int or larger. – Thanatos Feb 15 '13 at 08:14
  • 2
    well, it can be a quite big problem actually. If you send 100000 integers to javascript and asks it to summarize, the floating point problems might give you quite strange answers. That is why I found this question. – Nicklas Avén Jun 02 '13 at 21:30
2

Use this:

function int(a) { return Math.floor(a); }

And yo can use it like this:

var result = int(2.1 + 8.7 + 9.3); //int(20.1)
alert(result);                     //alerts 20
qwertymk
  • 34,200
  • 28
  • 121
  • 184
0

There is zero support for integers. It should be a simple matter of rounding off a variable every time you need it. The performance overhead isn't bad at all.

0

If you really need to use integers, just use the floor method on each number you encounter.

Other than that, the loose typing of Javascript is one of it's strengths.

ryebr3ad
  • 1,228
  • 3
  • 12
  • 20