Java program that reads in two floating-point numbers and tests whether they are the same
Posted by Samath
Last Updated: May 08, 2021

Write a program that reads in two floating­point numbers and tests whether they are the same up to two decimal places. Here are two sample runs:

     Enter a floating-point number: 3.0
     Enter a floating-point number: 3.0
     They are the same

     Enter a floating-point number: 2.0
     Enter a floating-point number: 3.01
     They are different.

Code:

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		double n1;
		double n2;
		
	    System.out.print("Enter 1st number: ");
	    n1 = input.nextDouble();
	    
	    System.out.print("Enter 2nd number: ");
	    n2 = input.nextDouble();
	    input.close();
	
	    if (Math.abs(n1 - n2) <= 0.01) {
	        System.out.println("They are the same");
	    }
	    else {
	        System.out.println("They are different");
	    }
	}
}