Numbers and Math
BigInt Arithmetic
BigInt is Dart's arbitrary-precision integer. Build values with BigInt.parse(text) for decimal text or BigInt.from(int) to widen an ordinary int. The usual operators +, -, *, ~/ stay exact on BigInt operands no matter how large, so they handle magnitudes the 64-bit int cannot represent. BigInt.toString() is the full decimal expansion.
Program
Play the program to parse a 21-digit BigInt, double it, integer-divide it, and count its decimal digits.
bigint.dart
Replay: real traced execution (multi-file project)
void main() {
var big = BigInt.parse('100000000000000000000');
var two = BigInt.from(2);
var doubled = big * two;
var halved = big ~/ two;
var digits = big.toString().length;
print('$doubled $halved digits=$digits');
}
big ← 100000000000000000000 (BigInt)
1void main() {2 var big = BigInt.parse('100000000000000000000');3 var two = BigInt.from(2);values this step100000000000000000000 (BigInt)bigtwo ← 2 (BigInt)
2var big = BigInt.parse('100000000000000000000');3var two = BigInt.from(2);4var doubled = big * two;values this step2 (BigInt)twodoubled ← 200000000000000000000 (BigInt)
3var two = BigInt.from(2);4var doubled = big * two;5var halved = big ~/ two;values this step200000000000000000000 (BigInt)doubledhalved ← 50000000000000000000 (BigInt)
4var doubled = big * two;5var halved = big ~/ two;6var digits = big.toString().length;values this step50000000000000000000 (BigInt)halveddigits ← 21 (int)
5var halved = big ~/ two;6var digits = big.toString().length;7print('$doubled $halved digits=$digits');values this step21 (int)digits100000000000000000000bigprint('$doubled $halved digits=$digits');
6 var digits = big.toString().length;7 print('$doubled $halved digits=$digits');8}output200000000000000000000 50000000000000000000 digits=21values this step200000000000000000000doubled50000000000000000000halved21digits
Follow the Values
bigstarts as100000000000000000000.twois2.doubledbecomes200000000000000000000.halvedbecomes50000000000000000000.- The decimal text has
21digits, so the program printsdigits=21. | name | value | | --- | --- | |big| 100000000000000000000 | |doubled| 200000000000000000000 | |halved| 50000000000000000000 | | digits | 21 |
BigInt.parse
`BigInt.parse(decimal)` reads arbitrary-precision integers from text. There is no overflow on the parsed value.
BigInt.from
`BigInt.from(int)` widens an ordinary `int` to a `BigInt` so it can mix with other `BigInt` operands.
exact arithmetic
`+`, `*`, `~/` on `BigInt` operands stay exact regardless of magnitude; the result is another `BigInt`.
Exercise: bigint.dart
Reproduce the doubled value and digits=21, then identify which printed value is half of big.