Numbers and Math
Double Methods
double exposes useful methods to round a value to a nearby integer (.floor(), .ceil(), .round()), keep a value inside a range with .clamp(), and format fixed-decimal text with .toStringAsFixed(). Each rounding method returns an int; clamp keeps a double receiver as double; toStringAsFixed returns a String.
Program
Play the program to round 3.7 three different ways, clamp it into a range, and format it with two fixed decimals.
double_methods.dart
Replay: real traced execution (multi-file project)
void main() {
double value = 3.7;
var down = value.floor();
var up = value.ceil();
var near = value.round();
var bounded = value.clamp(0.0, 3.0);
var fixed = value.toStringAsFixed(2);
print('$down $up $near $bounded $fixed');
}
value ← 3.7 (double)
1void main() {2 double value = 3.7;3 var down = value.floor();values this step3.7 (double)valuedown ← 3 (int)
2double value = 3.7;3var down = value.floor();4var up = value.ceil();values this step3 (int)down3.7valueup ← 4 (int)
3var down = value.floor();4var up = value.ceil();5var near = value.round();values this step4 (int)up3.7valuenear ← 4 (int)
4var up = value.ceil();5var near = value.round();6var bounded = value.clamp(0.0, 3.0);values this step4 (int)near3.7valuebounded ← 3.0 (double, clamped)
5var near = value.round();6var bounded = value.clamp(0.0, 3.0);7var fixed = value.toStringAsFixed(2);values this step3.0 (double, clamped)bounded3.7valuefixed ← 3.70 (String)
6var bounded = value.clamp(0.0, 3.0);7var fixed = value.toStringAsFixed(2);8print('$down $up $near $bounded $fixed');values this step3.70 (String)fixed3.7valueprint('$down $up $near $bounded $fixed');
7 var fixed = value.toStringAsFixed(2);8 print('$down $up $near $bounded $fixed');9}output3 4 4 3.0 3.70values this step3down4up4near3.0bounded3.70fixed
Follow the Values
valuestarts as3.7.floorgives3,ceilgives4, androundgives4.clampkeeps the shown value at3.0.toStringAsFixed(2)gives3.70.- The program prints
3 4 4 3.0 3.70. | result name | value | | --- | --- | | down | 3 | | up | 4 | | near | 4 | | bounded | 3.0 | | fixed | 3.70 |
floor and ceil
`.floor()` rounds toward negative infinity; `.ceil()` rounds toward positive infinity. Both return `int`.
round
`.round()` rounds halfway cases away from zero and returns an `int`. `3.7.round()` is `4`.
clamp
`.clamp(lo, hi)` keeps a value inside a range. With a `double` receiver, the result is a `double`; here `3.7` is capped to `3.0`.
toStringAsFixed
`.toStringAsFixed(n)` formats a `double` with exactly `n` digits after the decimal point and returns a `String`.
Exercise: double_methods.dart
Reproduce 3 4 4 3.0 3.70, then identify which result is formatted text with two decimal places.