Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

decimalAdjust #822

Open
char0n opened this issue Feb 9, 2019 · 0 comments
Open

decimalAdjust #822

char0n opened this issue Feb 9, 2019 · 0 comments

Comments

@char0n
Copy link
Owner

char0n commented Feb 9, 2019

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 char0n changed the title Decimal number adjust decimalAdjust Jan 4, 2020
@char0n char0n added the Hacktoberfest Hacktoberfest 2020 label Sep 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant