如何在颤动中自定义舍入?

How to customize the round off in flutter?

flutter中如何自定义四舍五入小数为0.1时自动向上舍入,小数小于0.1时自动向下舍入

例如:

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

您在问题中提供的信息不正确。根据文档:

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.

此外,您的代码片段甚至不会 运行。尝试 运行宁:

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

输出与文档一致:Returns the integer closest to this.
但是你的问题是问一些不同的东西,如果你想有一个自定义的圆形函数,你可以定义你自己的圆形函数或创建一个扩展:

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());
}

查看 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 了解更多信息。