Skip to content

Commit

Permalink
fix formatting, more intelligible file size stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
alyssaruth committed Sep 18, 2024
1 parent a7fbcac commit 4c3a0f4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
21 changes: 13 additions & 8 deletions core/src/main/kotlin/utils/MathsUtil.kt
Original file line number Diff line number Diff line change
@@ -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) =
Expand All @@ -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))
}
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)
)
}
2 changes: 2 additions & 0 deletions core/src/test/kotlin/utils/MathsUtilTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}

0 comments on commit 4c3a0f4

Please sign in to comment.