parseToUnits function
Parse a decimal string to smallest-unit BigInt (pure BigInt, no float).
Implementation
BigInt parseToUnits(String amount, int decimals) {
if (decimals < 0) {
throw ArgumentError('Invalid decimals: $decimals');
}
if (!_amountRegex.hasMatch(amount)) {
throw ArgumentError('Invalid amount: "$amount"');
}
final negative = amount.startsWith('-');
final stripped = negative ? amount.substring(1) : amount;
final parts = stripped.split('.');
final whole = parts[0];
final fraction = parts.length > 1 ? parts[1] : '';
if (fraction.length > decimals) {
throw ArgumentError(
'Too many decimal places: "$amount" has ${fraction.length} but max is $decimals',
);
}
final paddedFraction = fraction.padRight(decimals, '0');
final wholePart = whole.isEmpty ? BigInt.zero : BigInt.parse(whole);
final fractionPart = paddedFraction.isEmpty
? BigInt.zero
: BigInt.parse(paddedFraction);
final result = wholePart * BigInt.from(10).pow(decimals) + fractionPart;
return negative ? -result : result;
}