0
//Works on Dartpad

main() {
  var pi = 3.14; //3.14159265359
  var numbers = 0;
  dynamic result = 1.2;

  while (result.runtimeType == double) {
    numbers++;
    result = numbers * pi;
  }
  print('$result / $numbers = $pi');
}

//Works on local

main() {
  var pi = 3.14; //3.14159265359
  var numbers = 0;
  dynamic result = 1.2;
  while ((result - result.truncate()) != 0) {
    numbers++;
    result = numbers * pi;
  }
  print('${result.truncate()} / $numbers = $pi');
}

The problem is whenever you initialize a double variable, the dartpad can convert it to an integer when it becomes an integer but the local compiler doesn't do that. Could this be caused by js? Because as far as I know dartpad compiles with js.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Doca
  • 37
  • 6
  • 2
    The problem comes from JavaScript which does not have `int` but only `double` as a type to represent numbers. Dart does try hide this fact but the smell of JavaScript does sometimes penetrate the nice layer of abstraction. – julemand101 Jan 17 '22 at 12:23
  • 1
    Some more details about this: https://stackoverflow.com/questions/67108395/why-dart-infers-the-variable-type-as-a-int-when-i-explicitly-say-the-type-is-dou – julemand101 Jan 17 '22 at 12:24
  • 1
    Also, never use `.runtimeType == SomeType` when `is SomeType` will work. In this case, you would find that all JS numbers satisfy `is double`, and some also satisfy `is int` (those with no fractional part). (I generally recommend never using `runtimeType` for anything.) – lrn Jan 17 '22 at 16:46

1 Answers1

2

What you are observing is Dart trying to hide the limitation of JavaScript where numbers is always represented as double objects (so no int). Since DartPad is compiling your code to JavaScript and then executes it in your browser, you will get this behavior.

For more details I recommend looking at this StackOverflow question where I have made a detailed example that shows how numbers in Dart behave when running your program natively and as JavaScript: Why dart infers the variable type as a int when I explicitly say the type is double?

julemand101
  • 28,470
  • 5
  • 52
  • 48