Floating Data Types
There are 2 data types, that store floating point values, they are:
- float
- double
float
A float
is a single-precision 32-bit floating point number.
- Occupies
4
bytes. - The default value is `0.0F`.
- It can store a min value of
-2^149
and a maximum value of2^127
.
By default, decimals are interpreted as doubles. To create a float
, append an f
to the decimal literal.
A float
is precise to roughly an error of 1 in 10 million.
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
Float.NaN
NaN
stands for the results of an operation that cannot be determined. Such as dividing two infinite values.
public class FloatType {
public static void main(String[] args) {
float f1 = 0f;
float f2 = -0f;
System.out.println(f1 == f2); // true
System.out.println(1f / f1); // Infinity
System.out.println(1f / f2); // -Infinity
System.out.println(Float.POSITIVE_INFINITY / Float.POSITIVE_INFINITY); // NaN
}
}
0f
and -0f
are different but ==
yields true.
public class FloatType {
public static void main(String[] args) {
// addition
float add = 37.2f + -2.6f; // result: 34.6
System.out.println(add);
// subtraction
float subtract = 45.1f - 10.3f; // result: 34.8
System.out.println(subtract);
// multiplication
float multiply = 26.3f * 1.7f; // result: 44.71
System.out.println(multiply);
// division
float division = 37.1f / 4.8f; // result: 7.729166
System.out.println(division);
// modulus
float modulus = 37.1f % 4.8f; // result: 3.4999971
System.out.println(modulus);
}
}
double
A double
is a double-precision 64-bit floating point number.
- Occupies
8
bytes. - The default value is `0.0D`.
- It can store a min value of
-2^1074
and a maximum value of2^1023
.
public class DoubleType {
public static void main(String[] args) {
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
}
}
public class DoubleType {
public static void main(String[] args) {
double A = -7162.37;
double B = 974.21;
double C = 658.7;
double addedDoubles = B + C; // 315.51
double subtractedDoubles = B - C; // 1632.91
double scientificNotationDouble = 1.2e-3; // 0.0012
}
}