1

I use this:

FilteringTextInputFormatter.allow(
  RegExp(r'(^\d*\.?\d{0,2})'),
)

And it works fine but I cannot use comma, only dots. For some currencies the dot is used to separate thousands and the comma for the decimals.

How could I accept both?

Dani
  • 3,128
  • 2
  • 43
  • 91
  • 3
    I think this is a Regex question, not a Flutter one. See if [this](https://stackoverflow.com/q/16148034/9997212) helps. – enzo May 17 '21 at 22:24
  • Perhaps like this? `\b\d{1,3}(?:([.,])\d{3})*(?:(?!\1)[.,]\d{2})?\b` https://regex101.com/r/0ItMqg/1 – The fourth bird May 29 '21 at 10:12
  • with that I cannot type either commas or dots. Maybe I pasted it wrong? RegExp(r'^\d{1,3}(?:([.,])\d{3})*(?:(?!\1)[.,]\d{2})?') – Dani May 29 '21 at 10:31

1 Answers1

4

You can add a deny constructor at the beginning and replace , with .:

TextField(
  keyboardType: TextInputType.numberWithOptions(decimal: true),
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.deny(',', replacementString: '.')
    FilteringTextInputFormatter.allow(RegExp(r'(^\d*\.?\d{0,2})')),
  ],
)

If you need to keep the system separator by https://pub.dev/packages/intl, you can pre-define it and then use it in RegExp

import 'dart:ui' as ui;
import 'package:intl/number_symbols_data.dart' show numberFormatSymbols;

...

String locale = '${ui.window.locale.languageCode}_${ui.window.locale.countryCode}';
if (!numberFormatSymbols.keys.contains(locale))
  locale = ui.window.locale.languageCode;
final separator = numberFormatSymbols[locale]?.DECIMAL_SEP ?? '.';

...

TextField(
  keyboardType: TextInputType.numberWithOptions(decimal: true),
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.allow(RegExp('(^\\d*$separator?\\d{0,2})')),
  ],
)
Alex
  • 1,457
  • 1
  • 13
  • 26