Amount.convert constructor

Amount.convert({
  1. required num value,
  2. required int decimals,
})

Converts the given value to the smallest unit of the currency

Implementation

factory Amount.convert({
  required num value,
  required int decimals,
}) {
  var value_s = value.toExactString;

  final parts = value_s.split('.');

  var dec = parts.length == 1 ? 0 : parts[1].length;

  if (dec > decimals) {
    value_s = value_s.substring(0, value_s.length - (dec - decimals));
    dec = decimals;
  }

  var value_int = BigInt.tryParse(value_s.replaceAll('.', ''));

  if (value_int == null) {
    throw Exception('Invalid value: $value');
  }

  value_int = value_int * BigInt.from(10).pow(decimals.toInt() - dec);

  return Amount(
    value: value_int,
    decimals: decimals,
  );
}