"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ensureDecimals = exports.roundToPrecision = exports.roundToDecimal = exports.getNumberOfDecimals = void 0;

const getNumberOfDecimals = num => {
  const postDecimalString = (num + '').split('.')[1];
  return postDecimalString ? postDecimalString.length : 0;
};

exports.getNumberOfDecimals = getNumberOfDecimals;

const roundToDecimal = (number, precision) => {
  const factor = Math.pow(10, precision);
  return Math.round(number * factor) / factor;
};

exports.roundToDecimal = roundToDecimal;

const roundToPrecision = (number, precision) => {
  const decimalString = roundToDecimal(number, precision).toString();
  const numberOfDigitsBeforePeriod = decimalString.split('.')[0].length;
  const actualPrecision = Math.max(precision - numberOfDigitsBeforePeriod, 0);
  return roundToDecimal(number, actualPrecision);
};

exports.roundToPrecision = roundToPrecision;

const ensureDecimals = (number, targetDecimals = 0) => {
  const numberOfDecimals = getNumberOfDecimals(number);
  let numberToAdd = targetDecimals - numberOfDecimals;

  if (!numberToAdd) {
    return number;
  }

  let result = number + (numberOfDecimals === 0 ? '.' : '');

  while (numberToAdd--) {
    result += '0';
  }

  return result;
};

exports.ensureDecimals = ensureDecimals;