Page 72 - JavaScript
P. 72

Rounding


        Math.round() will round the value to the closest integer using half round up to break ties.


         var a = Math.round(2.3);       // a is now 2
         var b = Math.round(2.7);       // b is now 3
         var c = Math.round(2.5);       // c is now 3


        But


         var c = Math.round(-2.7);       // c is now -3
         var c = Math.round(-2.5);       // c is now -2


        Note how -2.5 is rounded to -2. This is because half-way values are always rounded up, that is
        they're rounded to the integer with the next higher value.




        Rounding up


        Math.ceil() will round the value up.


         var a = Math.ceil(2.3);        // a is now 3
         var b = Math.ceil(2.7);        // b is now 3


        ceiling a negative number will round towards zero


         var c = Math.ceil(-1.1);       // c is now 1




        Rounding down


        Math.floor() will round the value down.


         var a = Math.floor(2.3);        // a is now 2
         var b = Math.floor(2.7);        // b is now 2

        flooring a negative number will round it away from zero.



         var c = Math.floor(-1.1);       // c is now -1



        Truncating


        Caveat: using bitwise operators (except >>>) only applies to numbers between -2147483649 and
        2147483648.


         2.3  | 0;                       // 2 (floor)
         -2.3 | 0;                       // -2 (ceil)



        https://riptutorial.com/                                                                               29
   67   68   69   70   71   72   73   74   75   76   77