Numbers and Math
Math Functions and Constants
The dart:math library adds common math helpers on top of the int/double operators: max(a, b) and min(a, b) pick the larger or smaller of two values; sqrt(x) returns the square root as a double; pow(x, y) raises one number to another; the constant pi is the IEEE-754 double closest to the true value. Combine pi, round(), and / to format a fixed-decimal approximation without a printf.
Program
Play the program to compare two numbers, take a square root, raise a power, and round pi to two decimal places.
dart_math.dart
Replay: real traced execution (multi-file project)
import 'dart:math';
void main() {
var biggest = max(12, 7);
var smallest = min(12, 7);
var root = sqrt(144);
var cube = pow(2, 10);
var rounded = (pi * 100).round() / 100;
print('$biggest $smallest $root $cube $rounded');
}
biggest ← 12 (int)
3void main() {4 var biggest = max(12, 7);5 var smallest = min(12, 7);values this step12 (int)biggestsmallest ← 7 (int)
4var biggest = max(12, 7);5var smallest = min(12, 7);6var root = sqrt(144);values this step7 (int)smallestroot ← 12.0 (double)
5var smallest = min(12, 7);6var root = sqrt(144);7var cube = pow(2, 10);values this step12.0 (double)rootcube ← 1024 (num)
6var root = sqrt(144);7var cube = pow(2, 10);8var rounded = (pi * 100).round() / 100;values this step1024 (num)cuberounded ← 3.14 (double)
7var cube = pow(2, 10);8var rounded = (pi * 100).round() / 100;9print('$biggest $smallest $root $cube $rounded');values this step3.14 (double)rounded3.141592653589793piprint('$biggest $smallest $root $cube $rounded');
8 var rounded = (pi * 100).round() / 100;9 print('$biggest $smallest $root $cube $rounded');10}output12 7 12.0 1024 3.14values this step12biggest7smallest12.0root1024cube3.14rounded
Follow the Values
max(12, 7)gives12.min(12, 7)gives7.sqrt(144)gives12.0.pow(2, 10)gives1024.- Rounded
pigives3.14, so the program prints12 7 12.0 1024 3.14. | expression | result | | --- | --- | |max(12, 7)| 12 | |min(12, 7)| 7 | |sqrt(144)| 12.0 | |pow(2, 10)| 1024 | | roundedpi| 3.14 |
max and min
`max(a, b)` and `min(a, b)` return whichever operand wins; when both operands are `int`, the result stays `int`.
sqrt and pow
`sqrt(x)` returns a `double` square root; `pow(x, y)` returns `num` and picks `int` automatically when both operands are non-negative `int`.
pi
`pi` is the IEEE-754 `double` closest to the true value of pi. `(pi * 100).round() / 100` builds a 2-decimal approximation without `toStringAsFixed`.
Exercise: dart_math.dart
Reproduce 12 7 12.0 1024 3.14, then match each printed value to the expression that produced it.