round.js
55 lines
| 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 | |
| 35 | if (isHalf) { |
| 36 | switch (mode) { |
| 37 | case '2': |
| 38 | case 'PHP_ROUND_HALF_DOWN': |
| 39 | value = f + (sgn < 0); // rounds .5 toward zero |
| 40 | break; |
| 41 | case '3': |
| 42 | case 'PHP_ROUND_HALF_EVEN': |
| 43 | value = f + (f % 2 * sgn); // rouds .5 towards the next even integer |
| 44 | break; |
| 45 | case '4': |
| 46 | case 'PHP_ROUND_HALF_ODD': |
| 47 | value = f + !(f % 2); // rounds .5 towards the next odd integer |
| 48 | break; |
| 49 | default: |
| 50 | value = f + (sgn > 0); // rounds .5 away from zero |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return (isHalf ? value : Math.round(value)) / m; |
| 55 | } |