Skip to content

Instantly share code, notes, and snippets.

@ctran
Last active October 14, 2020 19:07
Show Gist options
  • Save ctran/5c55023708515b6e915484aa291e224b to your computer and use it in GitHub Desktop.
Save ctran/5c55023708515b6e915484aa291e224b to your computer and use it in GitHub Desktop.
filesize to human
// Convert a number of bytes to a more readable string
// Written this way (with attrs), as I was using it for a Grails taglib
def filesize = {
attrs ->labels = [' bytes', 'KB', 'MB', 'GB', 'TB']
size = attrs.size
label = labels.find {
if (size < 1024) {
true
}
else {
size /= 1024
false
}
}
"${new java.text.DecimalFormat( attrs.format ?: '0.##' ).format( size )}$label"
}
assert filesize([size: 1000]) == '1000 bytes'
assert filesize([size: 1024]) == '1KB'
assert filesize([size: 10000000]) == '9.54MB'
assert filesize([size: 10000000, format: '0.000']) == '9.537MB'
assert filesize([size: 10000000, format: '0']) == '10MB'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment