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.

round10.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Decimal adjustment of a number.
  3. *
  4. * @param {String} type The type of adjustment.
  5. * @param {Number} value The number.
  6. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
  7. * @returns {Number} The adjusted value.
  8. */
  9. var decimalAdjust = exports.decimalAdjust = function(type, value, exp) {
  10. // If the exp is undefined or zero...
  11. if (typeof exp === 'undefined' || +exp === 0) {
  12. return Math[type](value);
  13. }
  14. value = +value;
  15. exp = +exp;
  16. // If the value is not a number or the exp is not an integer...
  17. if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
  18. return NaN;
  19. }
  20. // Shift
  21. value = value.toString().split('e');
  22. value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  23. // Shift back
  24. value = value.toString().split('e');
  25. return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  26. }
  27. module.exports = {
  28. round10: function(value, exp) {
  29. return decimalAdjust('round', value, exp);
  30. },
  31. floor10: function(value, exp) {
  32. return decimalAdjust('floor', value, exp);
  33. },
  34. ceil10: function(value, exp) {
  35. return decimalAdjust('ceil', value, exp);
  36. },
  37. };
  38. module.exports.polyfill = function() {
  39. // Decimal round
  40. if (!Math.round10) {
  41. Math.round10 = module.exports.round10;
  42. }
  43. // Decimal floor
  44. if (!Math.floor10) {
  45. Math.floor10 = module.exports.floor10;
  46. }
  47. // Decimal ceil
  48. if (!Math.ceil10) {
  49. Math.ceil10 = module.exports.ceil10;
  50. }
  51. };