How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Kotlin

1 Answer

0 votes
fun main() {
    println(formatBytes(9823453784599))
    println(formatBytes(7124362542))
    println(formatBytes(23746178))
    println(formatBytes(1048576))
    println(formatBytes(1024000))
    println(formatBytes(873445))
    println(formatBytes(1024))
    println(formatBytes(978))
    println(formatBytes(13))
    println(formatBytes(0))
}

fun formatBytes(bytes: Long): String {
    val sizes = arrayOf("B", "KB", "MB", "GB", "TB")
    var i = 0
    var dblByte = bytes.toDouble()
    var remainingBytes = bytes

    while (i < sizes.size && remainingBytes >= 1024) {
        dblByte = remainingBytes / 1024.0
        remainingBytes /= 1024
        i++
    }

    return String.format("%.2f %s", dblByte, sizes[i])
}

 
 
/*
run:
   
8.93 TB
6.63 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0.00 B
   
*/

 



answered Nov 24, 2024 by avibootz
...