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
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');
}
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`.