import { Decimal } from "decimal.js";

export function numberFormat(x) {
  const reg = /^-?(0|[1-9]\d*)(\.\d{0,20})?$/;
  return reg.test(x) ? parseFloat(x) : 0;
}

export function add(x, y, precision = 2) {
  x = numberFormat(x);
  y = numberFormat(y);
  return new Decimal(x).plus(y).toFixed(precision);
}

export function minus(x, y, precision = 2) {
  x = numberFormat(x);
  y = numberFormat(y);
  return new Decimal(x).minus(y).toFixed(precision);
}

export function divide(x, y, precision = 2) {
  x = numberFormat(x);
  y = numberFormat(y);
  if (y === 0) {
    return new Decimal(0).toFixed(precision);
  }
  return new Decimal(x).div(y).toFixed(precision);
}

export function multiply(x, y, precision = 2) {
  x = numberFormat(x);
  y = numberFormat(y);
  return new Decimal(x).mul(y).toFixed(precision);
}
