toSats method

BigInt toSats(
  1. String amount
)

Obtains the number of satoshis from a string representation of this unit.

Numbers must only contain digits and optionally one decimal point (".") in the event that there are any decimals. Ensure that there is at least one digit before and after the decimal point. There may only be decimals upto decimals in number. Zeros are striped from the left and stripped from the right after the decimal point.

May throw BadAmountString if the number is not formatted correctly.

Implementation

BigInt toSats(String amount) {

  // Check format
  if (!_numberRegex.hasMatch(amount)) throw BadAmountString();

  // Split decimal
  final split = amount.split(".");
  final includesPoint = split.length == 2;

  // Decimal places must not exceed expected decimals
  if (includesPoint && split[1].length > decimals) throw BadAmountString();

  // Parse both sides into BigInt
  final left = BigInt.parse(split[0]);
  final right = includesPoint
    ? BigInt.parse(split[1].padRight(decimals, "0"))
    : BigInt.zero;

  return left*satsPerUnit + right;

}