Search code examples
flutterdoubletextfieldtextformfield

Converting negative number in the string format to double


When i use double.parse on my textfield input i get the following error FormatException (FormatException: Invalid double -). Saw a similar post but problem doesn't seem to be solve

Also how can i prevent user from entering two "." and "-" . Any help is much appreciated. Ty for your time

 TextFormField(
          inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^-?\d*.?\d*')),],
          keyboardType: TextInputType.numberWithOptions(signed: true,decimal: true),

          onChanged:(value) {
            setState(() {
              data = double.parse(value);
            });
          },
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'data'
          ),

        ),

I tried using RegExp('[0-9.-]') but it doesn't work as well. I still get back the same error message as stated above


Solution

  • double.parse is expecting a double as string. So when you enter a dot (.) or a dash (-) and it tries to parse it as a double, it throws an exception. You need to apply some checks in order to solve this.

    Try this

    TextFormField(
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp(r'^-?\d*.?\d*')),
          ],
          keyboardType:
              TextInputType.numberWithOptions(signed: true, decimal: true),
          onChanged: (value) {
            if (value.isNotEmpty && value != '.' && value != '-') {
              setState(() {
                data = double.parse(value);
              });
            }
          },
          decoration:
              InputDecoration(border: OutlineInputBorder(), labelText: 'data'),
        ),