Duration: do not use scientific format for large values

The largest duration value formatted in ns with maximal decimals
would fit in 40 chars.
This commit is contained in:
Ilya Gorbunov
2021-07-06 04:21:42 +03:00
committed by Space
parent 1be1e5279c
commit 3f6e2be687
7 changed files with 37 additions and 47 deletions
+6 -7
View File
@@ -783,7 +783,10 @@ public value class Duration internal constructor(private val rawValue: Long) : C
* and formatted with the specified [decimals] number of digits after decimal point.
*
* Special cases:
* - the infinite duration is formatted as `"Infinity"` without unit
* - an infinite duration is formatted as `"Infinity"` or `"-Infinity"` without a unit.
*
* @param decimals the number of digits after decimal point to show. The value must be non-negative.
* No more than 12 decimals will be shown, even if a larger number is requested.
*
* @return the value of duration in the specified [unit] followed by that unit abbreviated name: `d`, `h`, `m`, `s`, `ms`, `us`, or `ns`.
*
@@ -795,10 +798,7 @@ public value class Duration internal constructor(private val rawValue: Long) : C
require(decimals >= 0) { "decimals must be not negative, but was $decimals" }
val number = toDouble(unit)
if (number.isInfinite()) return number.toString()
return when {
abs(number) < 1e14 -> formatToExactDecimals(number, decimals.coerceAtMost(12))
else -> formatScientific(number)
} + unit.shortName()
return formatToExactDecimals(number, decimals.coerceAtMost(12)) + unit.shortName()
}
@@ -1211,5 +1211,4 @@ private fun millisToNanos(millis: Long): Long = millis * NANOS_IN_MILLIS
internal expect fun formatToExactDecimals(value: Double, decimals: Int): String
internal expect fun formatUpToDecimals(value: Double, decimals: Int): String
internal expect fun formatScientific(value: Double): String
internal expect fun formatUpToDecimals(value: Double, decimals: Int): String