A double
is a double-precision 64-bit IEEE 754 floating point number.
double example = -7162.37;
double myDouble = 974.21;
double anotherDouble = 658.7;
double addedDoubles = myDouble + anotherDouble; // 315.51
double subtractedDoubles = myDouble - anotherDouble; // 1632.91
double scientificNotationDouble = 1.2e-3; // 0.0012
Because of the way floating point numbers are stored, many numbers don't have an exact representation.
double notExact = 1.32 - 0.42; // result should be 0.9
System.out.println(notExact); // 0.9000000000000001
While using double
is fine for most applications, neither float
nor double
should be used to store precise numbers such as currency. Instead, the BigDecimal
class should be used
The default value of a double
is 0.0d
public double defaultDouble; // defaultDouble == 0.0
Note: Double.POSITIVE_INFINITY
, Double.NEGATIVE_INFINITY
, Double.NaN
are double
values. NaN
stands for results of operations that cannot be determined, such as dividing 2 infinite values. Furthermore 0d
and -0d
are different, but ==
yields true:
double d1 = 0d;
double d2 = -0d;
System.out.println(d1 == d2); // true
System.out.println(1d / d1); // Infinity
System.out.println(1d / d2); // -Infinity
System.out.println(Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY); // NaN