Home > Software engineering >  floating value formatting in TextFormField in Flutter
floating value formatting in TextFormField in Flutter

Time:06-06

I want to add restriction on user input and force to type fractional value. But if I type .5 it causes invalid input exception but 0.5 works fine. But user may type .5 instead of 0.5. So is there any way to that. Here is my code:

inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r"[0-9.]")),
        TextInputFormatter.withFunction((oldValue, newValue) {
          try {
            final text = newValue.text;
            if (text.isNotEmpty) double.parse(text);
            return newValue;
          } catch (e) {}
          return oldValue;
        }),
      ],

CodePudding user response:

That's because .5 is not parse-able to double you can add this line
if(text.startsWith('.')) text = '0$text';
before the if statement, so the code becomes:

try {
  String text = newValue.text;
  if (text.startsWith('.')) text = '0$text';
  if (text.isNotEmpty) double.parse(text);
  return newValue;
} catch (e) {}
return oldValue;
  • Related