TSR
TSR

Reputation: 20597

Dart Double to String is sometimes 5900.0 sometimes 5900

Based on Flutter 1.26.0-17.8.pre Dart SDK 2.10.4 (from Dart Pad)

void main() {
  double num = 5900.0;
  if (num.toString() == "5900.0") {
    print(true);
  } else {
    print(false);
  }
}

Evaluate false,

Based on Flutter (Channel unknown, 1.26.0-17.8.pre, on macOS 11.0.1 20B29 darwin-x64, locale en-GB)

The same code above evaluates true

The documentation does not say anything about which one is correct https://api.dart.dev/stable/2.10.5/dart-core/double/toString.html

Upvotes: 1

Views: 84

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17141

This is related to compilation to javascript. Javascript does not have a distinction between floating-point and integral data types. There are just "numbers". When you run in DartPad you're compiling to javascript and losing the typing information from that .0.

Running in the VM does not have this behavior as there is a distinction between the types.

If you believe this is a real issue, you can report it, but I believe I've seen something similar before already and it will be dismissed. As you mentioned, the toString documentation makes no claims about its exact output, just that it can be parsed back.

Additionally, do not use reserved keywords, e.g. num, as variable names.

Upvotes: 2

Related Questions