Dani
Dani

Reputation: 4186

Flutter: detect if a string can be converted to double

I can do something like this:

double.parse(myString)

That's fine when I have "1.1" but if I have "1.1.1" it fails with Invalid double. Could I detect this somehow in advance?

I'd need this for input validations

Upvotes: 1

Views: 1792

Answers (3)

Robert Sandberg
Robert Sandberg

Reputation: 8637

As written above, use double.tryParse() or wrap double.parse() with try catch

An alternative, if you need to do input validation could be filter away "bad" input already when the user inputs the number.

You could change keyboard type and use input formatters on a TextField / TextFormFiel

TextField(
  decoration: new InputDecoration(labelText: "Enter your number"),
  keyboardType: TextInputType.number,
  inputFormatters: <TextInputFormatter> [
    FilteringTextInputFormatter.digitsOnly
  ], // Only numbers can be entered
),

Upvotes: 1

benjlin
benjlin

Reputation: 31

You could write something like this

if(!myString.contains(<someregex>)) {
  double.parse(myString);
} 

Where the regex is validating that the string is a valid double, the value of doing this over using tryParse is that you can include your business rule validation alongside your datatype validation.

Upvotes: 0

Dani
Dani

Reputation: 4186

Working with

 double.tryParse(myString)

Upvotes: 2

Related Questions