You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1.2 KiB

4 years ago
  1. var root = require('./_root'),
  2. toInteger = require('./toInteger'),
  3. toNumber = require('./toNumber'),
  4. toString = require('./toString');
  5. /* Built-in method references for those with the same name as other `lodash` methods. */
  6. var nativeIsFinite = root.isFinite,
  7. nativeMin = Math.min;
  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. */
  15. function 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 && nativeIsFinite(number)) {
  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. pair = (toString(value) + 'e').split('e');
  26. return +(pair[0] + 'e' + (+pair[1] - precision));
  27. }
  28. return func(number);
  29. };
  30. }
  31. module.exports = createRound;