Home > Blockchain >  How to customize the round off in flutter?
How to customize the round off in flutter?

Time:05-27

How to customize round off in flutter when the decimal is 0.1 it will automatically round up but when the decimal is below 0.1 it will automatically round down

For example:

double roundUp = 0.1;
double roundedUp = roundUp.round() // it will become roundedUp = 1
double roundUp = 0.09;
double roundedDown = roundDown.round() // it will become roundedDown = 0

CodePudding user response:

The information you provide in your question is incorrect. As per the docs:

int round ()
Returns the integer closest to this.

Rounds away from zero when there is no closest integer: (3.5).round() == 4 and (-3.5).round() == -4.

Also your code snippet, as it is, won't even run. Try running:

void main() {
  print(0.1.round()); //prints 0
  print(0.09.round()); //prints 0
}

The output is in accordance with the docs: Returns the integer closest to this.
However your question is asking something different, if you want to have a custom round function, you could define your own round function or create an extension:

int roundDouble(double x) {
  return x.toInt();
}

extension Rounding on double {
  int myRound() {
    return this.toInt();
  }
}


void main() {
  print(roundDouble(5.2));
  print(5.2.myRound());
}

Check https://api.dart.dev/stable/2.3.0/dart-core/num/round.html and https://api.dart.dev/stable/2.17.1/dart-core/dart-core-library.html for more information.

  • Related