matt
matt

Reputation: 209

Difference between int and double

Why would anyone use int instead of double?

It seems to be that double is much more flexible than int.

Upvotes: 16

Views: 143476

Answers (4)

IDDQD
IDDQD

Reputation: 3751

Short answer:

int uses up four bytes of memory (and it cannot contain a decimal), and double uses eight bytes of memory. There are just different tools for different purposes.

Upvotes: -1

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

int and double have different semantics. Consider division. 1/2 is 0, 1.0/2.0 is 0.5. In any given situation, one of those answers will be right and the other wrong.

That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int. Languages such as Java that support integer types make truncation automatic for integer variables.

In addition to having different semantics from double, int arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.

Upvotes: 33

Barmar
Barmar

Reputation: 782508

Operations on integers are exact. double is a floating point data type, and floating point operations are approximate whenever there's a fraction.

double also takes up twice as much space as int in many implementations (e.g. most 32-bit systems) .

Upvotes: 9

Jesson Atherton
Jesson Atherton

Reputation: 654

int is a binary representation of a whole number, double is a double-precision floating point number.

Upvotes: 1

Related Questions