Skip to content

There is no way to check if a potentially constant double is NaN #53614

Closed as not planned
@mateusfccp

Description

@mateusfccp

According to the the IEEE-754 specification, NaN is never equal to any double, even to NaN (!!). Because of this, if one wants to know if a given double is NaN, they should use .isNaN instead.

See also #44649 and #50481, which are related to a lint to prevent comparison with NaN (like myDouble == double.nan).

The problem is that we have no way to check if a potentially constant value is NaN.

Example:

// Tentative 1: won't work, as the comparison will always return false
final class NonNanDouble {
  const NonNanDouble(this.value) : assert(value != double.nan); // A double can't equal 'double.nan', so the condition is always 'true'. Try using `double.isNaN', or removing the condition.

  final double value;
}

// Tentative 2: won't even compile, as `value.isNaN` is not a constant value
final class NonNanDouble {
  const NonNanDouble(this.value) : assert(value.isNaN); // Invalid constant value

  final double value;
}

If we want to do this check we have to resign the constant constructor.

// Workaround: now we can't have constant values for the class
final class NonNanDouble {
  NonNanDouble(this.value) : assert(value.isNaN);

  final double value;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions