JAVASCRIPT   26

round

Guest on 7th May 2022 02:12:19 AM

  1. function round (value, precision, mode) {
  2.   // http://kevin.vanzonneveld.net
  3.   // +   original by: Philip Peterson
  4.   // +    revised by: Onno Marsman
  5.   // +      input by: Greenseed
  6.   // +    revised by: T.Wild
  7.   // +      input by: meo
  8.   // +      input by: William
  9.   // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  10.   // +      input by: Josep Sanz (http://www.ws3.es/)
  11.   // +    revised by: Rafaإ‚ Kukawski (http://blog.kukawski.pl/)
  12. /)// %        note 1: Great work. Ideas for improvement:
  13. t:// %        note 1:  - code more compliant with developer guidelines
  14. es// %        note 1:  - for implementing PHP constant arguments look at
  15. at// %        note 1:  the pathinfo() function, it offers the greatest
  16. st// %        note 1:  flexibility & compatibility possible
  17. le// *     example 1: round(1241757, -3);
  18. );// *     returns 1: 1242000
  19. 00// *     example 2: round(3.6);
  20. );// *     returns 2: 4
  21.  4// *     example 3: round(2.835, 2);
  22. );// *     returns 3: 2.84
  23. 84// *     example 4: round(1.1749999999999, 2);
  24. );// *     returns 4: 1.17
  25. 17// *     example 5: round(58551.799999999996, 2);
  26. );// *     returns 5: 58551.8
  27. .8
  28.   var m, f, isHalf, sg// helper variables
  29. es
  30.   precision |= // making sure precision is integer
  31. er
  32.   m = Math.pow(10, precision);
  33.   value *= m;
  34.   sgn = (value > 0) | -(value < 0// sign of the number
  35. er
  36.   isHalf = value % 1 === 0.5 * sgn;
  37.   f = Math.floor(value);
  38.  
  39.   if (isHalf) {
  40.     switch (mode) {
  41.       case '2':
  42.       case 'PHP_ROUND_HALF_DOWN':
  43.         value = f + (sgn < 0// rounds .5 toward zero
  44. ro
  45.       break;
  46.       case '3':
  47.       case 'PHP_ROUND_HALF_EVEN':
  48.         value = f + (f % 2 * sgn// rouds .5 towards the next even integer
  49. er
  50.       break;
  51.       case '4':
  52.       case 'PHP_ROUND_HALF_ODD':
  53.         value = f + !(f % 2// rounds .5 towards the next odd integer
  54. er
  55.       break;
  56.       default:
  57.         value = f + (sgn > 0// rounds .5 away from zero
  58. ro
  59.     }
  60.   }
  61.  
  62.   return (isHalf ? value : Math.round(value)) / m

Raw Paste


Login or Register to edit or fork this paste. It's free.