Number Types: Floating-point Types
Rounding errors occur when an exact conversion between numbers is not possible
double f = 4.35;
System.out.println(100 * f); // prints 434.99999999999994
Click here to see how to store 4.35 in a memory boxdouble data type has 8 bytes = 64 bits
4.35 = 100.01 0110 0110 0110 0110 0110 ...in binary
Java: Illegal to assign a floating-point expression to an integer variable
double balance = 13.75;
int dollars = balance; // Error
Casts: used to convert a value to a different type
int dollars = (int) balance; // OK
Cast discards fractional part.
Math.round converts a floating-point number to nearest integer
long rounded = Math.round(balance);
// if balance is 13.75, then rounded is set to 14
Round a floating number into two decimal places.
import java.util.Scanner; public class RoundNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a floating number"); double x = input.nextDouble(); double HundredTimes = x * 100; double y = Math.round(HundredTimes) / 100.0 ; System.out.println("Round "+x + " into two decimal places: " + y); } }