MiniDecimal.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* eslint-disable max-classes-per-file */
  2. import BigIntDecimal from "./BigIntDecimal";
  3. import NumberDecimal from "./NumberDecimal";
  4. import { trimNumber } from "./numberUtil";
  5. import { supportBigInt } from "./supportUtil";
  6. // Still support origin export
  7. export { NumberDecimal, BigIntDecimal };
  8. export default function getMiniDecimal(value) {
  9. // We use BigInt here.
  10. // Will fallback to Number if not support.
  11. if (supportBigInt()) {
  12. return new BigIntDecimal(value);
  13. }
  14. return new NumberDecimal(value);
  15. }
  16. /**
  17. * Align the logic of toFixed to around like 1.5 => 2.
  18. * If set `cutOnly`, will just remove the over decimal part.
  19. */
  20. export function toFixed(numStr, separatorStr, precision) {
  21. var cutOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  22. if (numStr === '') {
  23. return '';
  24. }
  25. var _trimNumber = trimNumber(numStr),
  26. negativeStr = _trimNumber.negativeStr,
  27. integerStr = _trimNumber.integerStr,
  28. decimalStr = _trimNumber.decimalStr;
  29. var precisionDecimalStr = "".concat(separatorStr).concat(decimalStr);
  30. var numberWithoutDecimal = "".concat(negativeStr).concat(integerStr);
  31. if (precision >= 0) {
  32. // We will get last + 1 number to check if need advanced number
  33. var advancedNum = Number(decimalStr[precision]);
  34. if (advancedNum >= 5 && !cutOnly) {
  35. var advancedDecimal = getMiniDecimal(numStr).add("".concat(negativeStr, "0.").concat('0'.repeat(precision)).concat(10 - advancedNum));
  36. return toFixed(advancedDecimal.toString(), separatorStr, precision, cutOnly);
  37. }
  38. if (precision === 0) {
  39. return numberWithoutDecimal;
  40. }
  41. return "".concat(numberWithoutDecimal).concat(separatorStr).concat(decimalStr.padEnd(precision, '0').slice(0, precision));
  42. }
  43. if (precisionDecimalStr === '.0') {
  44. return numberWithoutDecimal;
  45. }
  46. return "".concat(numberWithoutDecimal).concat(precisionDecimalStr);
  47. }