How can a number be rounded up to the nearest whole number in Flutter?
- 0.1 => 1
- 1.5 => 2
- -0.1 => -1
The Num round
methods rounds to the nearest integer. How can one always round up?
How can a number be rounded up to the nearest whole number in Flutter?
The Num round
methods rounds to the nearest integer. How can one always round up?
You can use the .ceil()
method to achieve what you want.
Example:
print(-0.1.ceil()); => -1
print(1.5.ceil()); => 2
print(0.1.ceil()); => 1
To round up to the nearest whole number in an absolute sense, use ceil
if the number is positive and floor
if the number is smaller than 0.
The following function rounds numbers up to the closest integer.
static int roundUpAbsolute(double number) {
return number.isNegative ? number.floor() : number.ceil();
}
Or, use an extension function (6.3.roundUpAbs
).
extension Round on double {
int get roundUpAbs => this.isNegative ? this.floor() : this.ceil();
}