validAda function

Result<String, String> validAda({
  1. required String ada,
  2. int decimalPrecision = 6,
  3. bool allowNegative = false,
  4. bool zeroAllowed = false,
})

If ADA string is all digits, not negative and the correct decimal precision, then the normalized correct form is returned. If it's not legal, then an explanation is returned in the error message.

Implementation

Result<String, String> validAda({
  required String ada,
  int decimalPrecision = 6,
  bool allowNegative = false,
  bool zeroAllowed = false,
}) {
  ada = ada.trim();
  int invalidCharIndex = _firstIllegalDataChar(ada, allowNegative);
  if (invalidCharIndex > -1) {
    return Err(
        "invalid character: ${ada.substring(invalidCharIndex, invalidCharIndex + 1)}");
  }
  final amount = double.tryParse(ada) ?? 0.0;
  if (!zeroAllowed && amount == 0.0) return Err("can't be zero");
  final index = ada.lastIndexOf('.');
  final fraction =
      index >= 0 && index < ada.length ? ada.substring(index + 1) : '';
  if (fraction.length > decimalPrecision) {
    return Err("only $decimalPrecision decimal places allowed");
  }
  return Ok('$amount');
}