Java Program to Multiply Two Floating-Point Numbers
Floating-point numbers are numbers with a decimal point, such as 11.5 or 22.22. Java has two floating-point types: float (32-bit, about 7 significant digits) and double (64-bit, about 15–16 significant digits). double is the default and the better choice in most programs.
1. Multiply Using float and double
A float literal needs an f suffix, such as 11.5f; without it, Java treats the literal as a double. Both types store an approximation of most decimal values. float is printed with fewer digits, so its small error is rounded away, while double shows more digits and reveals the tiny difference.
public class MultiplyFloats {
public static void main(String[] args) {
float f1 = 11.5f;
float f2 = 22.22f;
float floatProduct = f1 * f2;
double d1 = 11.5;
double d2 = 22.22;
double doubleProduct = d1 * d2;
System.out.println("float: " + f1 + " x " + f2 + " = " + floatProduct);
System.out.println("double: " + d1 + " x " + d2 + " = " + doubleProduct);
}
}
float: 11.5 x 22.22 = 255.53 double: 11.5 x 22.22 = 255.52999999999997
2. Multiply Floating-Point Numbers with User Input
printf() with %.2f rounds the result to two decimal places, which hides small rounding errors in the last digits.
import java.util.Scanner;
public class MultiplyFloatsInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = scanner.nextDouble();
System.out.print("Enter second number: ");
double second = scanner.nextDouble();
scanner.close();
double product = first * second;
System.out.println("Product: " + product);
System.out.printf("Rounded: %.2f%n", product);
}
}
Enter first number: 1.1 Enter second number: 1.1 Product: 1.2100000000000002 Rounded: 1.21
3. Exact Multiplication Using BigDecimal
The previous output shows 1.1 × 1.1 as 1.2100000000000002, because 1.1 cannot be stored exactly in binary. BigDecimal stores decimal values exactly, which is why it is used for money.
import java.math.BigDecimal;
public class MultiplyBigDecimal {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("1.1");
BigDecimal b = new BigDecimal("1.1");
System.out.println("double: " + (1.1 * 1.1));
System.out.println("BigDecimal: " + a.multiply(b));
}
}
double: 1.2100000000000002 BigDecimal: 1.21
4. Summary
- Java's floating-point types are
float(add anfto literals) anddouble. doubleis more precise and is the default choice.- Floating-point results can contain tiny rounding errors; use
printf("%.2f")to display them neatly. - Use
BigDecimal.multiply()when the result must be exact.