Last active
October 14, 2020 19:07
-
-
Save ctran/5c55023708515b6e915484aa291e224b to your computer and use it in GitHub Desktop.
filesize to human
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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