Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - round down a double

Tags:

flutter

dart

How can round this down in dart/flutter:

int hours = int.parse((minutes/60).toStringAsFixed(0));

minutes/60 is 7.92, and I want the result to be 7 but it gets rounded up to 8...

like image 288
Christer Avatar asked Jun 18 '19 19:06

Christer


2 Answers

You can use both the Truncating division operator:

int hours = minutes ~/ 60;

Or the floor method:

int hours = (minutes/60).floor();
like image 71
Alexandre Ardhuin Avatar answered Oct 04 '22 15:10

Alexandre Ardhuin


If you need to round down with certain precision - use this:

double roundDown(double value, int precision) {
    final isNegative = value.isNegative;
    final mod = pow(10.0, precision);
    final roundDown = (((value.abs() * mod).floor()) / mod);
    return isNegative ? -roundDown : roundDown;
  }

roundDown(0.99, 1) => 0.9

roundDown(-0.19, 1) => -0.1

like image 43
Александр Бабич Avatar answered Oct 04 '22 13:10

Александр Бабич