Skip to Content

Round Java float and double numbers using Math.round

  1. /*
  2.   Round Java float and double numbers using Math.round
  3.   This java example shows how to round given float or double number using round
  4.   method of Java Math class.
  5. */
  6. public class RounFloatDoubleNumbersExample {
  7.  
  8.   public static void main(String[] args) {
  9.    
  10.     /*
  11.      * To round float number, use
  12.      * static int round(float f) method of Java Math class.
  13.      *
  14.      * It returns closest int number to the argument.
  15.      * Internally, it adds 0.5 to the argument, takes floor value and casts
  16.      * the result into int.
  17.      *
  18.      * i.e. result = (int) Math.floor( argument value + 0.5f )
  19.      */
  20.    
  21.      //returns same value
  22.      System.out.println(Math.round(10f));
  23.    
  24.      // returns (int) Math.floor(10.6) = 10
  25.      System.out.println(Math.round(20.5f));
  26.    
  27.      //returns (int) Math.floor(20.5 + 0.5) = 30
  28.      System.out.println(Math.round(20.5f));
  29.    
  30.      //returns (int) Math.floor(-18.9) = 19
  31.      System.out.println(Math.round(-19.4f));
  32.    
  33.      //returns (int) Math.floor(-23) = -23
  34.      System.out.println(Math.round(-23.5f));
  35.    
  36.      /*
  37.       * To round double numbers, use
  38.       * static long round(double d) method of Java Math class.
  39.       * It returns long.
  40.       */
  41.   }
  42. }
  43.  
  44. /*
  45. Output would be
  46. 10
  47. 21
  48. 21
  49. -19
  50. -23
  51. */