decimalFormatter static method

List<TextInputFormatter> decimalFormatter({
  1. int? decimalRange,
})

decimalFormatter allows numeric input including a single decimal point. decimalRange specifies the maximum number of digits allowed after the decimal point.

Implementation

static List<TextInputFormatter> decimalFormatter({int? decimalRange}) {
  if (decimalRange == null) {
    // Default: allow any number of decimals
    return [FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*'))];
  } else {
    return [
      TextInputFormatter.withFunction((oldValue, newValue) {
        final text = newValue.text;
        final regExp =
            RegExp(r'^\d*\.?\d{0,' + decimalRange.toString() + r'}$');
        if (regExp.hasMatch(text)) {
          return newValue;
        }
        return oldValue;
      }),
    ];
  }
}