15

Why would anyone use int instead of double?

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

2
  • All the other (visible) questions from the OP is about Java (some were untagged), so Java can be presumed. May 17, 2022 at 15:56
  • 2
    (The OP has left the building - "Last seen more than 7 years ago ".) May 17, 2022 at 15:57

4 Answers 4

33

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.

9

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

3
  • 1
    Afaik double and int are both 64bit on 64bit architectures. May 9, 2014 at 1:07
  • I clarified that it's most 32-bit systems.
    – Barmar
    May 9, 2014 at 1:08
  • 1
    Perfect! Keep in mind int as a C datatype can be 16bit on a 32bit machine! May 9, 2014 at 1:10
1

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

0
-1

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.

3
  • 2
    You will find that this is dependend on the environment and the language. c does not define the size of the int. May 9, 2014 at 1:03
  • True. Calling sizeof(int) is probably your best bet to be sure. But do you know if 2 byte integers exist anywhere now?
    – IDDQD
    May 9, 2014 at 1:10
  • 6
    Yes, C integers on the Arduino ( a popular electronics prototyping platform ) are 16 bits. May 9, 2014 at 1:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.