@yoroi/common
Version:
The Common package of Yoroi SDK
53 lines (52 loc) • 2.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseDecimal = parseDecimal;
var _bignumber = require("bignumber.js");
/**
* Parses a decimal number from a string and returns the parsed value as a BigNumber.
*
* @param value - The string to parse, negative sign is ignored.
* @param decimalPlaces - The number of decimal places to round (BigNumber.ROUND_DOWN).
* @param format - The locale format to use for formatting the parsed value.
*
* @returns An object containing the string and the parsed value as a BigNumber.
*/
function parseDecimal(_ref) {
let {
value,
decimalPlaces,
format
} = _ref;
const {
decimalSeparator
} = format;
const drop = new RegExp(`[^0-9${decimalSeparator}]`, 'g');
const cleanedText = value.toString().replaceAll(drop, '');
const sanitizedText = cleanedText.replace(decimalSeparator, '.');
const [intPart, decPart] = sanitizedText.split('.');
if (!decPart) {
const int = !intPart ? '0' : intPart;
const bn = new _bignumber.BigNumber(int).decimalPlaces(decimalPlaces, _bignumber.BigNumber.ROUND_DOWN);
const bi = BigInt(new _bignumber.BigNumber(int).decimalPlaces(decimalPlaces, _bignumber.BigNumber.ROUND_DOWN).shiftedBy(decimalPlaces).toFixed(0, _bignumber.BigNumber.ROUND_DOWN));
return {
text: cleanedText,
bn,
bi
};
}
const inputWithTrailing = `${intPart}.${decPart.slice(0, decimalPlaces)}1`;
const startsWithDecimal = sanitizedText.startsWith('.');
const formattedInput = new _bignumber.BigNumber(inputWithTrailing).toFormat(format).slice(0, -1);
const sanitizedInput = startsWithDecimal ? formattedInput.replace(`0${decimalSeparator}`, decimalSeparator) : formattedInput;
const numericValue = `${intPart}.${decPart}`;
const bn = new _bignumber.BigNumber(numericValue).decimalPlaces(decimalPlaces, _bignumber.BigNumber.ROUND_DOWN);
const bi = BigInt(bn.shiftedBy(decimalPlaces).toFixed(0, _bignumber.BigNumber.ROUND_DOWN));
return {
text: sanitizedInput,
bn,
bi
};
}
//# sourceMappingURL=parse-decimal.js.map