Currency constructor

Currency(
  1. String value
)

Implementation

Currency(String value) {
  value = value.split(',').join(''); // remove commas

  final BigInt ten = BigInt.from(10);
  final BigInt base = ten.pow(4);

  // Is it negative?
  bool negative = (value.substring(0, 1) == '-');

  if (negative) {
    value = value.substring(1);
  }

  if (value == '.') {
    throw Exception(
        'Invalid value ${pasc} cannot be converted to base unit with 4 decimals.');
  }

  // Split it into a whole and fractional part
  List<String> comps = value.split('.');

  String whole;
  String? fraction;

  if (comps.length > 2) {
    throw Exception('Too many decimal points');
  } else if (comps.length == 2) {
    fraction = comps[1];
  }
  whole = comps[0];

  if (whole == null) {
    whole = '0';
  }
  if (fraction == null) {
    fraction = '0';
  }
  if (fraction.length > 4) {
    throw Exception('Too many decimal places');
  }

  while (fraction!.length < 4) {
    fraction += '0';
  }

  BigInt wholeDec = BigInt.parse(whole);
  BigInt fractionDec = BigInt.parse(fraction);
  BigInt molina = wholeDec * base + fractionDec;

  if (negative) {
    molina = molina * BigInt.from(-1);
  }

  this.pasc = molina;
}