Zoltan Demant
02/22/2023, 10:55 AMkotlin.time.Duration? I thought this would be simple (it probably still is) but my first attempt didnt result in the behavior I was expecting, and Im not 100% clear on why that is (code for that in 🧵).
fun round(
duration: Long,
period: Long = 1000,
): Long {
val half = period / 2
return (duration + half) / period * period
}Zoltan Demant
02/22/2023, 10:56 AMfun round(
duration: Duration,
period: Duration = 1.seconds,
): Duration {
val half = period / 2
return (duration + half) / period * period
}Szymon Jeziorski
02/22/2023, 11:51 AM(duration + half) / period uses Long division meaning that entire decimal section is cut out, so that for example (9800 + 500) / 1000 gives 10, whereas Duration / Duration uses double division meaning above example would give 10.3.
If you want version with Duration to give same results as the one with Long you may for example use floor to ignore decimal part of division: floor((duration + half) / period) * periodKlitos Kyriacou
02/22/2023, 12:11 PMval periodNanos = period.inWholeNanoseconds
return ((duration + period / 2).inWholeNanoseconds / periodNanos * periodNanos).nanosecondsSzymon Jeziorski
02/22/2023, 12:35 PMKlitos Kyriacou
02/22/2023, 12:38 PMDuration.div(Int) instead. So it uses Long division for val half = period / 2 but indeed it uses Double division for dividing by period.Zoltan Demant
02/22/2023, 1:00 PM