Android Kotlin Convert File Size to Human Readable kB,MB,GB etc

masterjosh
by
masterjosh
Jan 10, 2019
Android Kotlin Convert File Size to Human Readable kB,MB,GB etc

Hi Dev,

this pretty little snippet am about to share, will allow you to convert file size in bytes to human readable format...

Fun/method code named fileSize


fun fileSize(size2:Int):String {
        val size = size2.toLong()
        if (size <= 0) return "0"
        val units = arrayOf("B", "kB", "MB", "GB", "TB")
        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
        return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups]
    }

are you have any problem using this code ?

i will be happy to help via comment section 

Happy Coding!




Add Comment