Skip to content

Instantly share code, notes, and snippets.

@gstraymond
Created July 5, 2018 09:48
Show Gist options
  • Save gstraymond/aa4b89dbf6f89128f5c8ae64fd62806a to your computer and use it in GitHub Desktop.
Save gstraymond/aa4b89dbf6f89128f5c8ae64fd62806a to your computer and use it in GitHub Desktop.
BytesLengthConverter
import java.lang.Math._
object LongExtensions {
implicit class BytesLengthConverter(val bytes: Long) extends AnyVal {
def humanReadableByteCount(si: Boolean = false): String = {
val unit = if (si) 1000 else 1024
if (bytes < unit) bytes + "B"
else {
val exp = (log(bytes) / log(unit)).toInt
val pre = (if (si) "kMGTPE" else "KMGTPE").charAt(exp - 1) + (if (si) "" else "i")
"%.1f%sB".format(bytes / pow(unit, exp), pre)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment