how to convert byte size into human readable format in java
Converting Byte Size into Human Readable Format in Kotlin
To convert a byte size into a human-readable format in Kotlin, you can use the following function:
fun formatByteSize(bytes: Long): String {
val units = arrayOf("B", "KB", "MB", "GB", "TB")
var size = bytes.toDouble()
var unit = 0
while (size >= 1024 && unit < units.size - 1) {
size /= 1024
unit++
}
return "%.2f %s".format(size, units[unit])
}
Let's break down the steps involved in this function:
The function
formatByteSize
takes abytes
parameter of typeLong
representing the byte size to be converted.An array
units
is defined, which contains the units of measurement for byte sizes (e.g., B, KB, MB, GB, TB).The variable
size
is initialized with the value ofbytes
converted to aDouble
.The variable
unit
is initialized to 0, representing the index of the unit in theunits
array.A while loop is used to divide the
size
by 1024 as long assize
is greater than or equal to 1024 andunit
is less than the index of the last unit in theunits
array. This loop allows us to determine the appropriate unit for the byte size.Inside the loop,
size
is divided by 1024 andunit
is incremented.Finally, the function returns a formatted string using the
size
andunit
values. The%.2f
format specifier is used to format thesize
with two decimal places, and the corresponding unit from theunits
array is appended.
Here's an example usage of the formatByteSize
function:
val byteSize = 128974848L
val formattedSize = formatByteSize(byteSize)
println("Formatted Size: $formattedSize")
Output:
Formatted Size: 122.93 MB
This function allows you to convert a byte size into a human-readable format, making it easier to understand and display byte sizes in a more user-friendly way.
[[SOURCE 1]]