Decimals
1public class Decimals {
2 public static void main(String[] args) {
3 int a = 10;
4 int b = 3;
5 System.out.println(a/b);
6
7 double c = 10;
8 double d = 3;
9 System.out.println(c/d);
10
11 double g = 4.5;
12 double h = 9.7;
13 System.out.println("4.5 + 9.7 = " + (g + h));
14
15 System.out.println("10 divided by 3 = " + (10/3));
16 System.out.println("5.5 divided by 0.54 = " + (5.5/0.54));
17
18 System.out.println("10 divided by 3 = " + (10/3));
19 System.out.println("10 divided by 3 = " + (10.0/3));
20 System.out.println("10 divided by 3 = " + (10/3.0));
21 System.out.println("10 divided by 3 = " + (10.0/3.0));
22 }
23}
Explanation
Remember a data type lets you specify what kind of data a variable can store.
In this program the
double
data type is introduced. Thedouble
data type lets you use and manipulate floating-point numbers (i.e. decimals). Floating point numbers are how computers store decimals. Remember the integer data type can only store whole numbers, which is why a different data type is needed for decimals. In Java, if you divide two integers, Java will always round downwards, as in line 18.If you divide a floating-point number by an integer (as in line 19), or an integer by a floating-point number (as in line 20), or a floating-point number by another floating-point number (as in line 21), then you get a floating-point number, and Java will not round. Java treats any number with a decimal point as a floating-point number, even if it is just
.0
, that is why10.0/3
will give3.333...
but10/3
will just give3
.However, if you assign an integer e.g.
10
to a variable that has adouble
as a data type, then it will be implicitly converted to adouble
. This is shown in lines 7 and 8.