Floating-point numbers in Java are used to represent fractional values or numbers with a large range of
possible values.
They are primarily used when precise decimal calculations are not required.
Java uses two primitive data types to represent floating-point numbers: float and double.
- The float data type is a 32-bit single-precision floating-point number
- The double data type (which we will use in this class rather than float) is a 64-bit
double-precision floating-point number.
This makes the double data type more accurate than the float data type.
We can create double variables and assign values to them using
the same syntax we used for the other types:
double payRate = 42.5;
The simplest way to convert a floating-point value to an integer
is to use a type cast, so called because it molds or “casts”
a value from one type to another.
The syntax for type casting is to put the name of the type
in parentheses and use it as an operator.
double payRate = 42.5;
int pay = (int) payRate;
What is the value of the variable pay?
Integer vs Floating Point Division
In math, division often allows for remainders.
It is why whenever a number is NOT evenly divisible by another number
it can result in a decimal number opposed to a whole number
e.g. 5/2 is equal to 2.5
However, integer division and division as we know from math class
(also known as floating-point division) are two different ways of performing division
operations.
Integer division is the division operation performed on two integers, resulting in an integer
quotient.
The result is obtained by discarding the fractional part of the division, if any.
In other words, it performs a "round towards zero" operation.
- For example, if you perform an integer division of 10 divided by 3, the result is 3 because it discards
the fractional part.
- Similarly, if you divide -10 by 3 using integer division, the result is -3, as it still rounds towards
zero.
On the other hand, floating-point division is the division operation performed on floating-point numbers
(those with decimal places).
It produces a result with decimal places, including the fractional part.
This type of division is typically more accurate and provides more precise results.
In Java, when dividing two integers using the '/' operator,
integer division is performed if both operands are integers.
To perform floating-point division, at least one of the operands should be a floating-point number.
For example:
int result = 10 / 3;//Integer division, result is 3
double result = 10.0 / 3;//Regular division, result is approximately 3.3333
It is important to be aware of the distinction between integer division and floating-point division,
especially when working with different data types and when precision is required in calculations.