double primitive Java data types are used to represent decimal numbers, where the key difference is the range of possible values. That is,
double has 64-bits available to use, while
float only has 32-bits. This means that
double can represent numbers with up to 15 digits after the decimal point, while
float can only represent 6 digits.
This fact also translates into the amount of memory required. For instance, a large Java ArrayList of primitive floats will hold less memory than one using doubles. It also may have an impact on, potentially, the performance of the underlying application too.
Table of Contents
The following points list the differences between
doublehas a greater precision than
float, it can represent longer numbers.
floatrepresents the number sign using 1 bit, a 8 bit exponent and 23 bit mantissa; on the other hand
doubleuses a 11 bit exponent and 52 bit mantissa.
- Their bit ranges are different, it is 64-bit in
doubleand 32-bit in
doubleis the default number representation in the JVM, to use
fsuffix notation is required.
double in Java are similar
The following points list the similarities between
doubleare primitive Java data types.
floatshares the same 64-bit machine value range limits as
doublecan be logically compared to each other with Java equals or not equals operators.
- They are both represent fractions using a decimal point and proceeding digits.
floatare real numbers, and not integers.
How to choose whether to use
double in your Java code
The main thing to consider is whether you have any size requirements or limits in your Java application. As noted, floating point numbers in Java require less memory space than
double. On the other hand, you should also consider whether you need the fact
double offers greater precision than
float in Java.
If this is a concern, you should also look into the BigDecimal Java class to see if it is more appropriate to use. That is, the target Java application you are working on, might dictate that you use a certain data type rather than you having the freedom to choose e.g., Investment Banking or Trading software.
If you do choose to use
float, then be aware you need to use the
f suffix notation everywhere in your Java code. This itself can be a little cumbersome, if you like writing clean code. Alternatively, you can always use the actual Float and Double Java classes instead of using Java primitive data types.