Write a Java program to accept a float value of number and return a rounded float value


This Java program prompts the user to enter a float number, and then rounds the number to the nearest integer using a custom method round_number. The result is printed to the console.

  • The program first creates a Scanner object called in to read user input from the console. It then prompts the user to enter a float number using the System.out.print statement and reads the user's input using the in.nextFloat() method. The entered number is assigned to the variable f.
  • The program then calls the round_number method, passing in f as an argument. This method takes the input float and rounds it to the nearest integer by checking whether the decimal part of the number is closer to the floor or ceiling of the number. The Math.floor() and Math.ceil() methods are used to calculate the floor and ceiling values of the input number, respectively. The method then returns the rounded number as a float.
  • Finally, the program prints both the original value of f and its rounded value using System.out.println.

Note that the program assumes that the rounding method should always round to the nearest integer. If you want to round to a different number of decimal places or to a specific value, you would need to modify the round_number method accordingly.

Source Code

import java.util.*;
public class Round_FloatNumber
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		System.out.print("Enter a float Number : ");
		float  f = in.nextFloat();  
		System.out.printf("Given value is : "+f);
		System.out.printf("\nRounded value is : "+round_number(f));
	}
	public static float round_number(float f)
	{
		float f_num = (float)Math.floor(f);
		float c_num = (float)Math.ceil(f);
		if ((f - f_num) > (c_num - f))
		{
				return c_num;
		}
		else if ((c_num - f) > (f - f_num)) 
		{
			return f_num;
		}
		else 
		{ 
		   return c_num; 
		}		
	}	
}

Output

Enter a float Number : 74.538
Given value is : 74.538
Rounded value is : 75.0

Enter a float Number : -74.245
Given value is : -74.245
Rounded value is : -74.0

Example Programs