round.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. // % note 1: - code more compliant with developer guidelines
  14. // % note 1: - for implementing PHP constant arguments look at
  15. // % note 1: the pathinfo() function, it offers the greatest
  16. // % note 1: flexibility & compatibility possible
  17. // * example 1: round(1241757, -3);
  18. // * returns 1: 1242000
  19. // * example 2: round(3.6);
  20. // * returns 2: 4
  21. // * example 3: round(2.835, 2);
  22. // * returns 3: 2.84
  23. // * example 4: round(1.1749999999999, 2);
  24. // * returns 4: 1.17
  25. // * example 5: round(58551.799999999996, 2);
  26. // * returns 5: 58551.8
  27. var m, f, isHalf, sgn; // helper variables
  28. precision |= 0; // making sure precision is integer
  29. m = Math.pow(10, precision);
  30. value *= m;
  31. sgn = (value > 0) | -(value < 0); // sign of the number
  32. isHalf = value % 1 === 0.5 * sgn;
  33. f = Math.floor(value);
  34. if (isHalf) {
  35. switch (mode) {
  36. case '2':
  37. case 'PHP_ROUND_HALF_DOWN':
  38. value = f + (sgn < 0); // rounds .5 toward zero
  39. break;
  40. case '3':
  41. case 'PHP_ROUND_HALF_EVEN':
  42. value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
  43. break;
  44. case '4':
  45. case 'PHP_ROUND_HALF_ODD':
  46. value = f + !(f % 2); // rounds .5 towards the next odd integer
  47. break;
  48. default:
  49. value = f + (sgn > 0); // rounds .5 away from zero
  50. }
  51. }
  52. return (isHalf ? value : Math.round(value)) / m;
  53. }