Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between int and double

Tags:

int

double

I was wondering if someone could tell me why anyone would use int instead of double? It seems to be that double is much more flexible than int.

Thanks

like image 404
matt Avatar asked May 09 '14 00:05

matt


People also ask

Why do we use double instead of int?

A very basic explanation is that a double can be a number with a decimal point. So with regards to the code you posted, because total is of type double it can be incremented by 0.5 after every loop total += 0.5 . If total was of type int this would not be possible.

Should I use double or int?

Use double for non-integer math where the most precise answer isn't necessary. Use decimal for non-integer math where precision is needed (e.g. money and currency). Use int by default for any integer-based operations that can use that type, as it will be more performant than short or long .

Is double A integer type?

integers are numbers without decimals. double is a floating-point numbers with double precisions. integer uses the same size of memory to describe a value of a higher range. Instead double is more precise (decimals) but You couldn't store too high number.


1 Answers

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.

like image 89
Patricia Shanahan Avatar answered Oct 10 '22 12:10

Patricia Shanahan