Java: Accepts two floatingpoint numbers and checks whether they are the same up to two decimal places
Compare Floats Up to Two Decimals
Write a Java program that accepts two floatingpoint numbers and checks whether they are the same up to two decimal places.
Test Data
Input first floatingpoint number: 1235
Input second floatingpoint number: 2534
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise32 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input first floatingpoint number: ");
double num1 = input.nextDouble();
System.out.print("Input second floatingpoint number: ");
double num2 = input.nextDouble();
input.close();
if (Math.abs(num1 - num2) <= 0.01) {
System.out.println("These numbers are the same.");
}
else {
System.out.println("These numbers are different.");
}
}
}
Sample Output:
Input first floatingpoint number: 1235 Input second floatingpoint number: 2534 These numbers are different.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to compare two floats for equality up to two decimal places by truncating the values.
- Write a Java program to check if two floating-point numbers are nearly equal up to two decimals using a defined epsilon.
- Write a Java program to convert two floats to BigDecimal with scale 2 and then check for equality.
- Write a Java program to format two floats using String.format("%.2f") and compare the resulting strings for equality.
Go to:
PREV : Compare Three Numbers (Equal, Different).
NEXT : Java Recursive Methoss exercises
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.