Last active
December 31, 2023 11:37
-
-
Save chris-hatton/a3fca4d064e7466982a8151d81715ca1 to your computer and use it in GitHub Desktop.
Human Readable Data Size Formatter for Kotlin Multiplatform (uses Common API only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package datasizeformatter | |
import kotlin.math.abs | |
import kotlin.math.pow | |
import kotlin.math.roundToLong | |
/** | |
* Format a human-readable representation of data size, in binary base form. | |
* e.g. 1024 -> 1 KiB | |
* @param byteCount The number of bytes to represent in human-readable form. `Long.MIN_VALUE` is unsupported. | |
* @param decimalPlaces The number of digits to round the resulting scale to | |
* @param zeroPadFraction whether to add trailing zeroes if they could otherwise be numerically truncated. | |
* e.g. for the value `3.1` if [decimalPlaces] is set to 3 and [zeroPadFraction] is `true` would be shown as `3.100`. | |
*/ | |
fun formatBinarySize( | |
byteCount: Long, | |
decimalPlaces: Int = 2, | |
zeroPadFraction: Boolean = false | |
): String { | |
require(byteCount>Long.MIN_VALUE) { "Out of range" } | |
require(decimalPlaces>=0) { "Negative decimal places unsupported" } | |
val isNegative = byteCount < 0 | |
val absByteCount = abs(byteCount) | |
return if (absByteCount < 1024) { | |
"$byteCount B" | |
} else { | |
val zeroBitCount: Int = (63 - absByteCount.countLeadingZeroBits()) / 10 | |
val absNumber: Double = absByteCount.toDouble() / (1L shl zeroBitCount * 10) | |
val roundingFactor: Int = 10.0.pow(decimalPlaces).toInt() | |
val absRoundedNumberString = with((absNumber * roundingFactor).roundToLong().toString()) { | |
val splitIndex = length - decimalPlaces - 1 | |
val wholeString = substring(0..splitIndex) | |
val fractionString = with(substring(splitIndex + 1)) { | |
if (zeroPadFraction) this else dropLastWhile { digit -> digit == '0' } | |
} | |
if (fractionString.isEmpty()) wholeString else "$wholeString.$fractionString" | |
} | |
val roundedNumberString = if(isNegative) "-$absRoundedNumberString" else absRoundedNumberString | |
"$roundedNumberString ${"KMGTPE"[zeroBitCount - 1]}iB" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested OK on JVM, JS and Native targets with: