Home E-Books Special Effects and Game Development in Java Double and Float

Special Effects and Game Development in Java(TM) - Double and Float

by Anibal Wainstein

1.2.4 Double and Float

There are two types of floating point numbers in Java: double and float. Double uses 64 bits to represent the number and have double the precision as float that only uses 32 bits. Floating point numbers work in the same way as integers when operating on the arithmetic operators. They can be declared in the following way:

double PI = 3.141592654;

float PI = 3.141592654;

1.2.5 Bytes

Bytes are whole numbers between 0 and 255. The arithmetic operators work with these in the same way as integers, but with the difference that a byte cannot be negative or bigger than 255.


1.2.6 Converting between integers and floating point numbers

Let us say you have two integers "x" and "y" and that you will be using these to draw a point on the screen later on. Assume also that we have two floating point numbers "a" and "b". They have the values:

float a = 7.5;

float b = 1.0;
We will now draw the sum as an x-coordinate and the difference as a y-coordinate. Since these numbers are floating point numbers then one may not set the variables "x" and "y" to go directly to these values. A special conversion is needed:
//"x" will contain 9 because 

//8.5 is rounded to 9

int x = (int)(a + b);       
//"y" will contain 7 because //6.5 is rounded to 7. int y = (int)(a - b);

This is called type casting. The floating point numbers are converted to integers. Observe that the variables "a" and "b" are not converted to integers during the conversion process. A variables type cannot change once it has been declared. We can also convert the other way:

a = (float) (x + y);

The sum is calculated, converted and the result is stored in the variable "a". Later I will be reviewing other uses for this. 

 

Next Page >>