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
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -7,15 +7,11 @@ package kotlin.time
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import kotlin.concurrent.getOrSet
private val rootNegativeExpFormatSymbols = DecimalFormatSymbols(Locale.ROOT).apply { exponentSeparator = "e" }
private val rootPositiveExpFormatSymbols = DecimalFormatSymbols(Locale.ROOT).apply { exponentSeparator = "e+" }
private val precisionFormats = Array(4) { ThreadLocal<DecimalFormat>() }
private fun createFormatForDecimals(decimals: Int) = DecimalFormat("0", rootNegativeExpFormatSymbols).apply {
private fun createFormatForDecimals(decimals: Int) = DecimalFormat("0").apply {
if (decimals > 0) minimumFractionDigits = decimals
roundingMode = RoundingMode.HALF_UP
}
@@ -32,11 +28,3 @@ internal actual fun formatUpToDecimals(value: Double, decimals: Int): String =
createFormatForDecimals(0)
.apply { maximumFractionDigits = decimals }
.format(value)
private val scientificFormat = ThreadLocal<DecimalFormat>()
internal actual fun formatScientific(value: Double): String =
scientificFormat.getOrSet { DecimalFormat("0E0", rootNegativeExpFormatSymbols).apply { minimumFractionDigits = 2 } }
.apply {
decimalFormatSymbols = if (value >= 1 || value <= -1) rootPositiveExpFormatSymbols else rootNegativeExpFormatSymbols
}
.format(value)