Jorkoh
05/29/2021, 12:43 PM// 18 minutes and 17.1 seconds => 1097.1 seconds => PT18M17.099999999S
val duration = 1097.1.toDuration(DurationUnit.SECONDS)
print(duration.toIsoString())
This loss of precision also exists if I use the toComponents
extension or inWholeX
accessorsdiesieben07
05/29/2021, 12:45 PMDouble
internally. Update to 1.5 and it should be fixed, it uses a Long now.Jorkoh
05/29/2021, 12:49 PMplugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.5.0'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib"
}
diesieben07
05/29/2021, 12:55 PMDouble
is a floating point number so inherently imprecise.
1097.1
cannot be represented as a double, you will actually get 1097.0999755859375
.diesieben07
05/29/2021, 12:58 PMDuration.seconds(1097) + Duration.milliseconds(100)
Jorkoh
05/29/2021, 1:47 PMDouble.toDuration
and convertDurationUnit(double)
are pretty much useless if they can't keep the correct nanoseconds value.
For example I can do
BigDecimal(1097.1).setScale(9, RoundingMode.HALF_EVEN).times(BigDecimal(1E9)).toLong()
and go from double seconds to long nanoseconds just fine. And I'm sure there are better ways to do the samediesieben07
05/29/2021, 1:50 PM1097.0999755859375
. The double value 1097.1
does not exist.Jorkoh
05/29/2021, 2:00 PMval doubleValue = 1097.1
println(doubleValue.toString())
and it will print 1097.1, JVM is smart enough to figure that out. I can write BigDecimal(1097.1).setScale(9, RoundingMode.HALF_EVEN)
and get a precise representation to 9 decimal values of the Double which is enough for a Duration type.Jorkoh
05/29/2021, 2:03 PMdiesieben07
05/29/2021, 2:59 PMDouble#toString
also doesn't print the actual stored FP value, it does some normalization stuff to print a "nice value". 0.1.toString() also prints 0.1, even though 0.1 cannot be exactly represented by either float or double. The same is true for 1097.1, it cannot be exactly represented by float or double.
Yes, you can use rounding, but having Duration
just round without any reason sounds bad. How much should it round? Which rounding mode? If you want rounding, do it yourself in whatever way you desire before passing it to Duration.diesieben07
05/29/2021, 3:01 PM