ramda-adjunct icon indicating copy to clipboard operation
ramda-adjunct copied to clipboard

decimalAdjust

Open char0n opened this issue 6 years ago • 0 comments

Is your feature request related to a problem? Please describe.

Decimal adjustment of a number.

Describe the solution you'd like

Possible implementation

/**
 * Decimal adjustment of a number.
 *
 * @param {String}  type  The type of adjustment.
 * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
 * @param {Number}  value The number.
 * @returns {Number} The adjusted value.
 */
function decimalAdjust(type, exp, value) {
  // If the exp is undefined or zero...
  if (typeof exp === 'undefined' || +exp === 0) {
    return Math[type](value);
  }
  value = +value;
  exp = +exp;
  // If the value is not a number or the exp is not an integer...
  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
    return NaN;
  }
  // Shift
  value = value.toString().split('e');
  value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Round
decimalAdjust('round', -1, 55.55);   // 55.6
decimalAdjust('round', -1, 55.549);  // 55.5
decimalAdjust('round', 1, 55);       // 60
decimalAdjust('round', 1, 54.9);     // 50
decimalAdjust('round', -1, -55.55);  // -55.5
decimalAdjust('round', -1, -55.551); // -55.6
decimalAdjust('round', 1, -55);      // -50
decimalAdjust('round', 1, -55.1);    // -60
// Floor
decimalAdjust('floor', -1, 55.59);   // 55.5
decimalAdjust('floor', 1, 59);       // 50
decimalAdjust('floor', -1, -55.51);  // -55.6
decimalAdjust('floor', 1, -51);      // -60
// Ceil
decimalAdjust('ceil', -1, 55.51);    // 55.6
decimalAdjust('ceil', 1, 51);        // 60
decimalAdjust('ceil', -1, -55.59);   // -55.5
decimalAdjust('ceil', 1, -59);       // -50

Describe alternatives you've considered

--

Additional context

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor#Decimal_adjustment

char0n avatar Feb 09 '19 11:02 char0n