UNPKG

ethers-maths

Version:

➗ Useful ethers-based math libraries to ease the journey through off-chain fixed-point arithmetics

31 lines (30 loc) 1.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toDecimals = exports.toFloat = exports.format = void 0; const ethers_1 = require("ethers"); const utils_1 = require("./utils"); const format = (x, decimals, digits) => { const formatted = (0, ethers_1.formatUnits)(x, decimals); let dotIndex = formatted.indexOf("."); if (dotIndex < 0) dotIndex = formatted.length; decimals = formatted.length - 1 - dotIndex; digits ?? (digits = decimals); return digits < decimals ? formatted.slice(0, dotIndex + (digits > 0 ? digits + 1 : 0)) : formatted + "0".repeat(digits - decimals); }; exports.format = format; const toFloat = (x, decimals) => { return parseFloat((0, exports.format)(x, decimals)); }; exports.toFloat = toFloat; const toDecimals = (x, decimals, scaleDecimals) => { x = (0, ethers_1.toBigInt)(x); if (decimals <= scaleDecimals) { const ratio = (0, utils_1.pow10)(scaleDecimals - decimals); return (x + ratio / 2n) / ratio; } return x * (0, utils_1.pow10)(decimals - scaleDecimals); }; exports.toDecimals = toDecimals;