Are there any libraries that provide an object/class with implicits conversions (from Int, Long, Float) for human readable file size units (like Duration).
With Duration
you can do this:
11.millis
1.5.minutes
10.hours
I wonder if there is some library that would allow me to do:
1.gibabyte
1024.megabytes
10.gibibytes
10.GB
50.GiB
I know I could implement this myself, but I'm trying to not reinvent the wheel.
Squants is a good solution, especially if you need more than just the human readable byte size conversion from the lib, but another possibility is to use this simple 4-line solution ported from an old SO java solution. You may not need the ZB and YB today, but maybe in the future ;)
/**
* @see https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
* @see https://en.wikipedia.org/wiki/Zettabyte
* @param fileSize Up to Exabytes
* @return
*/
def humanReadableByteSize(fileSize: Long): String = {
if(fileSize <= 0) return "0 B"
// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta
val units: Array[String] = Array("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
val digitGroup: Int = (Math.log10(fileSize)/Math.log10(1024)).toInt
f"${fileSize/Math.pow(1024, digitGroup)}%3.3f ${units(digitGroup)}"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With