Java program to round a number


The java.lang.Math.round(float a) returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Special cases −

  • If the argument is NaN, the result is 0.

  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.

  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Example

import java.util.Scanner;
public class RoundingDecimalPlaces {
   public static void main(String[] args) {
      System.out.println("Enter a string value ::");
      Scanner sc = new Scanner(System.in);
      float f = sc.nextFloat();
      System.out.println("Result of the given float after rounding:: " + Math.round(f));
   }
}

Output

Enter a string value ::
44584.2257
Result of the given float after rounding:: 44584

Updated on: 13-Mar-2020

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements