UNPKG

933 BJavaScriptView Raw
1import toInteger from './toInteger';
2import toNumber from './toNumber';
3import toString from './toString';
4
5/**
6 * Creates a function like `_.round`.
7 *
8 * @private
9 * @param {string} methodName The name of the `Math` method to use when rounding.
10 * @returns {Function} Returns the new round function.
11 */
12function createRound(methodName) {
13 var func = Math[methodName];
14 return function(number, precision) {
15 number = toNumber(number);
16 precision = toInteger(precision);
17 if (precision) {
18 // Shift with exponential notation to avoid floating-point issues.
19 // See [MDN](https://mdn.io/round#Examples) for more details.
20 var pair = (toString(number) + 'e').split('e'),
21 value = func(pair[0] + 'e' + (+pair[1] + precision));
22
23 pair = (toString(value) + 'e').split('e');
24 return +(pair[0] + 'e' + (+pair[1] - precision));
25 }
26 return func(number);
27 };
28}
29
30export default createRound;