Rounding float/double values to integer/long

  1. Casting float values into integer results in truncation.

    Example: float x; int i; x = 4.9F; i = (int) x; // i = 4

    (You can run this program and check for yourself: click here)

     

  2. Java's library has two function round that rounds floating point values up/down to an integer values.


    int round(float a) - rounds a float value to the nearest int long round(double a) - rounds a double value to the nearest long

  3. BUT... since Java does not allow "loose" functions...

    The round functions are contained in the Math class.


    To use the round functions, you must invoke:   Math.round(...)
        Example:
    
        float x;
        int   i;
    
        x = 4.9F;
        i = Math.round(x);      // i = 5
    

    (You can run this program and check for yourself: click here)

  4. Here is the link to the documentation of the Math class: click here

    **** Make a note that round is a static function... A.K.A. class method