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
@@ -15,13 +15,17 @@ internal actual fun formatToExactDecimals(value: Double, decimals: Int): String
val pow = 10.0.pow(decimals)
JsMath.round(abs(value) * pow) / pow * sign(value)
}
return rounded.asDynamic().toFixed(decimals).unsafeCast<String>()
return if (abs(rounded) < 1e21) {
// toFixed switches to scientific format after 1e21
rounded.asDynamic().toFixed(decimals).unsafeCast<String>()
} else {
// toPrecision outputs the specified number of digits, but only for positive numbers
val positive = abs(rounded)
val positiveString = positive.asDynamic().toPrecision(ceil(log10(positive)) + decimals).unsafeCast<String>()
if (rounded < 0) "-$positiveString" else positiveString
}
}
internal actual fun formatUpToDecimals(value: Double, decimals: Int): String {
return value.asDynamic().toLocaleString("en-us", json("maximumFractionDigits" to decimals)).unsafeCast<String>()
}
internal actual fun formatScientific(value: Double): String {
return value.asDynamic().toExponential(2).unsafeCast<String>()
}