In dart, as I am a newbie using extension, I want to make a simple extension to check value is double.

extension numberExtension on num{
  bool get isInteger => (this % 1) == 0;
  bool get isDouble =>double.tryParse(this) != null;
}

here isInteger is correct, but for isDouble I get this error:

The argument type 'num' can't be assigned to the parameter type 'String'

Problem is this in isDouble getter!?


Solution 1: supermuesli

Replace double.tryParse(this) != null with this is double


Solution 2: Top-Master

Assuming anything that is not an Integer is a Float or a Double;

Why not implement isDecimal instead, something like:

extension numberExtension on num {
  bool get isInteger => (this % 1) == 0;
  bool get isDecimal => (this % 1) != 0;
}

OR

extension numberExtension on num {
  bool get isInteger => this is int;
  bool get isDecimal => !(this is int);
}

Note that we could directly use "this is double" above,
but the "!(this is int)" check is simply more change-compatible, because it would even work if Dart ever adds some new num sub-type.


Update; looking into docs tells us that:

  • If compiled into JavaScript, there is no real int type, only doubles without decimal.
  • Dart does not seem to support 32-bit float, but has 64-bit double at least.
  • int is always 64-bit (just like double), but bitwise and/or shift operators truncate it into 32-bit (losing data or percision).

number-platform-specific


Solution 3: jamesdlin

Your original approach:

extension numberExtension on num {
  bool get isInteger => (this % 1) == 0;
  bool get isDouble =>double.tryParse(this) != null;
}

doesn't work because your extension is on num, so this is a num. double.tryParse expects to parse a String.

Why don't you just check if the object is an int or double directly?

extension numberExtension on num {
  bool get isInteger => this is int;
  bool get isDouble => this is double;
}

Of course, the extension is not very useful since x.isDouble is not much more convenient to use than using x is double directly, and the latter has the benefit of allowing automatic type-promotion to occur.

(Also, for Dart for the web, where int and double types are both backed by JavaScript numbers, numbers can be reported as both int and double, but using heuristics like % 1 and double.tryParse won't help with that.)