Reputation: 7919
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?
Upvotes: 17
Views: 22497
Reputation: 7919
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();
}
Upvotes: 8
Reputation: 14033
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
Upvotes: 32