UNPKG

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