From 4c3a0f407566cd5b48435c0d2c1662415c961db3 Mon Sep 17 00:00:00 2001 From: Alyssa Date: Wed, 18 Sep 2024 22:54:48 +0100 Subject: [PATCH] fix formatting, more intelligible file size stuff --- core/src/main/kotlin/utils/MathsUtil.kt | 21 +++++++++++++-------- core/src/test/kotlin/utils/MathsUtilTest.kt | 2 ++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/core/src/main/kotlin/utils/MathsUtil.kt b/core/src/main/kotlin/utils/MathsUtil.kt index a440200..a5ed961 100644 --- a/core/src/main/kotlin/utils/MathsUtil.kt +++ b/core/src/main/kotlin/utils/MathsUtil.kt @@ -1,4 +1,4 @@ -import kotlin.math.log2 +import kotlin.math.log import kotlin.math.pow fun getPercentage(count: Number, total: Number, digits: Int = 1) = @@ -20,10 +20,15 @@ private fun round(number: Double, decimalPlaces: Int): Double { return rounded / powerOfTen } -fun Long.formatAsFileSize(): String = log2(coerceAtLeast(1).toDouble()).toInt().div(10).let { - val precision = when (it) { - 0 -> 0; else -> 1; - } - val prefix = arrayOf("", "K", "M", "G", "T", "P", "E", "Z", "Y") - String.format("%.${precision}f ${prefix[it]}B", toDouble() / 2.0.pow(it * 10.0)) -} \ No newline at end of file +fun Long.formatAsFileSize(): String { + if (this == 0L) return "0 B" + + val magnitudeIndex = log(toDouble(), 1024.0).toInt() + val precision = if (magnitudeIndex == 0) 0 else 1 + val units = listOf("B", "KB", "MB", "GB", "TB") + + return String.format( + "%.${precision}f ${units[magnitudeIndex]}", + toDouble() / 1024.0.pow(magnitudeIndex) + ) +} diff --git a/core/src/test/kotlin/utils/MathsUtilTest.kt b/core/src/test/kotlin/utils/MathsUtilTest.kt index 83d8714..01443d6 100644 --- a/core/src/test/kotlin/utils/MathsUtilTest.kt +++ b/core/src/test/kotlin/utils/MathsUtilTest.kt @@ -40,9 +40,11 @@ class MathsUtilTest : AbstractTest() { @Test fun `Format as file size`() { + 0L.formatAsFileSize() shouldBe "0 B" 568L.formatAsFileSize() shouldBe "568 B" 1024L.formatAsFileSize() shouldBe "1.0 KB" 34304L.formatAsFileSize() shouldBe "33.5 KB" 5242880L.formatAsFileSize() shouldBe "5.0 MB" + 107374182400L.formatAsFileSize() shouldBe "100.0 GB" } }