
walkmc.extensions.numbers.Formatters.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of walk-server Show documentation
Show all versions of walk-server Show documentation
A spigot fork to kotlin structure and news.
@file:Suppress("NOTHING_TO_INLINE")
package walkmc.extensions.numbers
import walkmc.extensions.*
import walkmc.extensions.collections.*
import kotlin.time.*
import java.text.*
import java.util.*
/**
* Returns a [DecimalFormat] with a maximum fraction digits of 2.
*/
val DecimalFormatter by lazy {
DecimalFormat("##,###").apply { maximumFractionDigits = 2 }
}
/**
* Returns a [TreeMap] that's corresponds all suffixes to format.
*/
val FormatterSuffixes by lazy {
treeMapOf(
1E3 to "K", 1E6 to "M", 1E9 to "B", 1e12 to "T", 1e15 to "Q", 1e18 to "QQ", 1e21 to "S",
1e24 to "SS", 1E27 to "O", 1e30 to "N", 1e33 to "D", 1e36 to "UN", 1e39 to "DD", 1e42 to "TRD",
1e45 to "QD", 1e48 to "QND", 1e51 to "SD", 1e54 to "SPD", 1e57 to "OCD", 1e60 to "UND", 1e63 to "VG"
)
}
/**
* Returns this number formated as spaced, like:
* `1.000`, `15.591`
*/
fun Number.spaced(): String = DecimalFormatter.format(toDouble())
/**
* Returns this string number unspaced.
*/
fun String.unspaced() = replace(".", "").toDouble()
/**
* Returns this number formated with suffixes, like:
* `1K`, `15.59K`
*/
fun Number.format(): String {
val value = toDouble()
if (value < 1000) return value.toString()
val entry = FormatterSuffixes.floorEntry(value)
val number = value / (entry.key / 10) / 10
return number.spaced() + entry.value
}
/**
* Returns this number formated as time.
*
* The result will depend on the [unit], this only formats the [unit].
*
* The number is parsed as milliseconds.
*/
fun Number.formatSingleTime(
unit: DurationUnit = DurationUnit.SECONDS,
decimals: Int = 0,
): String = toLong().toDuration(unit).toString(unit, decimals)
/**
* Returns this number formated as time.
*
* This formats days, hours, minutes and seconds.
*/
fun Number.formatTime(unit: DurationUnit = DurationUnit.MILLISECONDS): String {
return toLong().toDuration(unit).format()
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy