toNumericString function

String toNumericString(
  1. String? inputString, {
  2. bool allowPeriod = false,
  3. bool allowHyphen = true,
  4. String mantissaSeparator = '.',
  5. String? errorText,
  6. bool allowAllZeroes = false,
  7. int? mantissaLength,
})

errorText if you don't want this method to throw any errors, pass null here allowAllZeroes might be useful e.g. for phone masks

Implementation

String toNumericString(
  String? inputString, {
  bool allowPeriod = false,
  bool allowHyphen = true,
  String mantissaSeparator = '.',
  String? errorText,
  bool allowAllZeroes = false,
  int? mantissaLength,
}) {
  if (inputString == null) {
    return '';
  } else if (inputString == '+') {
    return inputString;
  }
  // if (mantissaLength != null) {
  //   if (mantissaLength < 1) {
  //     /// a small hack to fix this https://github.com/caseyryan/flutter_multi_formatter/issues/136
  //     // inputString = inputString.replaceAll('.', '');
  //   }
  // }
  if (mantissaSeparator == '.') {
    inputString = inputString.replaceAll(',', '');
  } else if (mantissaSeparator == ',') {
    final fractionSep = _detectFractionSeparator(inputString);
    if (fractionSep != null) {
      inputString = inputString.replaceAll(fractionSep, '%FRAC%');
    }
    inputString = inputString.replaceAll('.', '').replaceAll('%FRAC%', '.');
  }
  var startsWithPeriod = numericStringStartsWithOrphanPeriod(
    inputString,
  );

  var regexWithoutPeriod = allowHyphen ? _digitRegExp : _positiveDigitRegExp;
  var regExp = allowPeriod ? _digitWithPeriodRegExp : regexWithoutPeriod;
  var result = inputString.splitMapJoin(
    regExp,
    onMatch: (m) => m.group(0)!,
    onNonMatch: (nm) => '',
  );
  if (startsWithPeriod && allowPeriod) {
    result = '0.$result';
  }
  if (result.isEmpty) {
    return result;
  }
  try {
    result = _toDoubleString(
      result,
      allowPeriod: allowPeriod,
      errorText: errorText,
      allowAllZeroes: allowAllZeroes,
    );
  } catch (e) {
    if (kDebugMode) {
      print(e);
    }
  }
  return result;
}