Duration: round Double value to Long ns instead of truncating it KT-47675

This commit is contained in:
Ilya Gorbunov
2021-06-29 03:42:35 +03:00
committed by Space
parent 42cd2e65e6
commit 255c4b405e
3 changed files with 9 additions and 8 deletions
+3 -2
View File
@@ -9,6 +9,7 @@ import kotlin.contracts.*
import kotlin.jvm.JvmInline
import kotlin.math.abs
import kotlin.math.roundToInt
import kotlin.math.roundToLong
import kotlin.math.sign
/**
@@ -816,11 +817,11 @@ public fun Long.toDuration(unit: DurationUnit): Duration {
public fun Double.toDuration(unit: DurationUnit): Duration {
val valueInNs = convertDurationUnit(this, unit, DurationUnit.NANOSECONDS)
require(!valueInNs.isNaN()) { "Duration value cannot be NaN." }
val nanos = valueInNs.toLong()
val nanos = valueInNs.roundToLong()
return if (nanos in -MAX_NANOS..MAX_NANOS) {
durationOfNanos(nanos)
} else {
val millis = convertDurationUnit(this, unit, DurationUnit.MILLISECONDS).toLong()
val millis = convertDurationUnit(this, unit, DurationUnit.MILLISECONDS).roundToLong()
durationOfMillisNormalized(millis)
}
}