_createRound.js 1.1 KB

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