Mister Smith
Mister Smith

Reputation: 28188

Dart: able to add 2 but not 1

I'm testing this snippet in DartPad:

import 'dart:math';

void main() {
  int ov = pow(2, 53);
  ov = ov + 0;
  print('$ov');
  ov = ov + 1;
  print('$ov');
  ov = ov + 2;
  print('$ov');
}

I'm new to Dart. I was trying to overflow the variable, but apparently Dart has arbitrary precission integers. The output is kind of surprising:

9007199254740992
9007199254740992
9007199254740994

Why am I able to add 2 but adding 1 does not have any effect?

Here is the pad if you want to check it.

Upvotes: 1

Views: 212

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76303

When dart is compiled to JS it relays on JS Number type for num (int or double). If you try the same things in a JS console you will get the same results:

> Math.pow(2, 53)
9007199254740992
> Math.pow(2, 53) + 1
9007199254740992
> Math.pow(2, 53) + 2
9007199254740994

Upvotes: 4

Related Questions