net.dankito.utils.FormatUtils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
The 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)
}
}
}
}