Search code examples
flutterdartfloating-point

Check if double or floating point number is within Flutter supported limits


I use the following method to determine if a user-input value is actually a double (floating point) number. This has been working well in what I meant it for originally. Now I am thinking of probably expanding the method to check if the floating point number input by user is within the range of Floating-point numbers supported by Flutter so as to avoid any crashes/freezes of my app on such input.

Question: Is the following method enough, already, to catch such exceptions? If not, please point to comprehensive resources clearly stating the range lowest to highest allowed floating point number in Flutter as the resources I found were not clear. I manually tested by appending a 101 (one hundred and one only) zeros to 1 i.e. 1.0e+101 without any error which is probably higher than any number my app is intended to process.

Code for my method:

bool is_double_input(String str) {
  double a = 0.0;
  int exception_caught = 0;
  try {
    a = double.parse(str);
  } catch (e) {
    exception_caught++;
  } finally {
    if (exception_caught == 0) {
      return true;
    } else {
      return false;
    }
  }
}

UPDATE 01: I manually tested by appending a 308 zeros to 1 i.e. 1.0e+308 without any error, but on 309th trailing zero the result of displaying double.toString(); results in displaying infinity instead of 1.0e+309 . I still don't know what/how to conclude.


Solution

  • First, you shouldn't have catch clauses that catch everything since such clauses will catch logical (programming) error such as assertion failures. If you want to handle failure from double.parse, you should explicitly catch FormatException. But really you instead should use double.tryParse.

    As you've empirically shown, you can't rely on double.parse/double.tryParse to fail when parsing a string that represents a number outside the range of an IEEE-754 double-precision floating-point number. If you just care that the number is finite and within the minimum and maximum finite values, you can do:

    bool is_double_input(String str) => (double.tryParse(str)?.isFinite) ?? false;
    

    Note that that won't tell you if value underflows (i.e., if it's too close to 0 to be representable as a double), but you might not care about that case.

    Also note that that does not distinguish between syntactically valid floating-point literals that are outside the range of double and invalid syntax. If you care to make the distinction, then you should check the result of double.tryParse separately from checking isFinite.