我最近开始使用Dart,并试图以每秒精度格式化数字倒计时时钟。
倒计时时,通常有一种精确但还不完美的表示时间的方法-因此,如果我在2分钟开始计时,并要求在经过一秒钟后显示当前时间,则几乎可以保证计时器将在1:58:999999(例如)上报告,如果使用 Duration.inSeconds()
发出该值,则将为118(秒),这是由于~/
运算符的工作方式所致,因为它会根据Duration的值四舍五入为整数微秒。
如果将值呈现为时钟,则一秒钟后时钟会从“2:00”变为“1:58”,最终将显示两次“0:00”,直到倒计时真正0:00:00。
作为人类,这似乎像时钟在跳动,所以我认为由于增量太小,我应该四舍五入到最接近的秒,这对于倒数计时器来说足够准确,并且可以处理以微秒为单位的微小误差。 / milli-seconds,以更好地为观看者服务。
我想出了这种secondRounder
方法:
Duration secondRounder(Duration duration) {
int roundedDuration;
if (duration.inMilliseconds > (duration.inSeconds * 1000)) {
roundedDuration = duration.inSeconds + 1;
} else {
roundedDuration = duration.inSeconds;
}
return new Duration(seconds: roundedDuration);
}
也可以在此DartPad中运行:https://dartpad.dartlang.org/2a08161c5f889e018938316237c0e810
由于我还不熟悉所有方法,因此我阅读了许多文档,这是迄今为止我提出的最好的文档。我想我正在寻找一种可能看起来像这样的方法:
roundedDuration = duration.ceil(nearest: millisecond)
有没有更好的方法可以解决我尚未想到的问题?
最佳答案
您可以将自己的方法“添加”到Duration
中作为扩展方法:
extension RoundDurationExtension on Duration {
/// Rounds the time of this duration up to the nearest multiple of [to].
Duration ceil(Duration to) {
int us = this.inMicroseconds;
int toUs = to.inMicroseconds.abs(); // Ignore if [to] is negative.
int mod = us % toUs;
if (mod != 0) {
return Duration(microseconds: us - mod + toUs);
}
return this;
}
}
那应该允许您编写
myDuration = myDuration.ceil(Duration(seconds: 1));
并将myDuration
舍入到最接近的秒数。
关于dart - 根据所需精度将持续时间四舍五入到最接近的秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801869/