【问题标题】:How to round a number up in Flutter?如何在 Flutter 中对数字进行四舍五入?
【发布时间】:2020-07-19 05:18:52
【问题描述】:

如何在 Flutter 中将数字四舍五入到最接近的整数?

  • 0.1 => 1
  • 1.5 => 2
  • -0.1 => -1

Num round 方法四舍五入到最接近的整数。一个人怎么能总是四舍五入?

【问题讨论】:

  • -0.1 => -1 不是“四舍五入”。 “四舍五入”的意思是“朝着正无穷大”。您要求的是从零四舍五入。

标签: flutter dart


【解决方案1】:

你可以使用.ceil()方法来实现你想要的。

例子:

print(-0.1.ceil()); => -1
print(1.5.ceil()); => 2
print(0.1.ceil()); => 1

【讨论】:

  • 这个答案也不正确。 double number = -0.1; number.ceil() => 0-0.1.ceil() 舍入到 -1 时,ceil 方法似乎先舍入数字然后应用符号。这可能是为什么 ceil 不正确的原因,如果数字是包含符号的变量。
【解决方案2】:

要在绝对意义上四舍五入到最接近的整数,如果数字为正数,请使用 ceil,如果数字小于 0,请使用 floor

以下函数将数字向上舍入到最接近的整数。

static int roundUpAbsolute(double number) {
  return number.isNegative ? number.floor() : number.ceil();
}

或者,使用扩展函数 (6.3.roundUpAbs)。

extension Round on double {
  int get roundUpAbs => this.isNegative ? this.floor() : this.ceil();
}

【讨论】:

  • 这个答案正确地四舍五入所有双打。 -0.1 舍入为 -1。您的答案没有正确舍入双变量。
猜你喜欢
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
相关资源
最近更新 更多