All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.FormatUtils.kt Maven / Gradle / Ivy

There is a newer version: 1.0.20
Show newest version
package net.dankito.utils


open class FormatUtils {

    companion object {
        const val KiloBits = 1000f
        const val MegaBits = KiloBits * KiloBits
        const val GigaBits = MegaBits * KiloBits

        const val KiloBytePowerOfTwo = 1024f
        const val MegaBytePowerOfTwo = KiloBytePowerOfTwo * KiloBytePowerOfTwo
        const val GigaBytePowerOfTwo = MegaBytePowerOfTwo * KiloBytePowerOfTwo
    }


    /**
     * Returns the file size in bytes by the power of two (1 kB = 1024 bytes).
     */
    open fun formatFileSize(fileSize: Long): String {
        return formatFileSize(fileSize.toFloat())
    }

    /**
     * Returns the file size in bytes by the power of two (1 kB = 1024 bytes).
     */
    open fun formatFileSize(fileSize: Float): String {
        when {
            fileSize > 0.1 * GigaBytePowerOfTwo -> {
                val value = fileSize / GigaBytePowerOfTwo
                return String.format("%.1f GB", value)
            }
            fileSize > 0.1 * MegaBytePowerOfTwo -> {
                val value = fileSize / MegaBytePowerOfTwo
                return String.format("%.1f MB", value)
            }
            else -> {
                val value = fileSize / KiloBytePowerOfTwo
                return String.format("%.1f kB", value)
            }
        }
    }


    /**
     * Returns the speed in bits per second (1 kBit = 1000 bits).
     */
    open fun formatSpeed(fileSizeInBytes: Long, durationInMillis: Long): String {
        return formatSpeed(fileSizeInBytes * 8 / durationInMillis.toFloat() * 1000)
    }

    /**
     * Returns the speed in bits per second (1 kBit = 1000 bits).
     */
    open fun formatSpeed(bitsPerSeconds: Long): String {
        return formatSpeed(bitsPerSeconds.toFloat())
    }

    /**
     * Returns the speed in bits per second (1 kBit = 1000 bits).
     */
    open fun formatSpeed(bitsPerSeconds: Float): String {
        when {
            bitsPerSeconds >= GigaBits / 10 -> {
                val value = bitsPerSeconds / GigaBits
                return String.format("%.1f GBit/s", value)
            }
            bitsPerSeconds >= MegaBits / 10 -> {
                val value = bitsPerSeconds / MegaBits
                return String.format("%.1f MBit/s", value)
            }
            else -> {
                val value = bitsPerSeconds / KiloBits
                return String.format("%.1f kBit/s", value)
            }
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy