Monday, August 15, 2016

Human Readable Byte Count

For Java:
public static String humanReadableByteCount(Long bytes,boolean si){
        int unit=si?1000:1024;
        if(bytes<unit){
            return bytes+" B";
        }
        int exp=(int)(Math.log(bytes)/Math.log(unit));
        return String.format("%.1f %sB",bytes/Math.pow(unit,exp),(si?"kMGTPE":"KMGTPE").charAt(exp-1)+(si?"":"i"));
    }

From Here

For JavaScript:
function humanReadableByteCount(bytes,si){
     var unit=si?1000:1024;
     if(bytes<unit){
         return bytes+" B";
     }
     var exp=Math.floor(Math.log(bytes)/Math.log(unit));
     return (bytes/Math.pow(unit,exp))+" "+(si?"kMGTPE":"KMGTPE").charAt(exp-1)+(si?"":"i")+"B";
 }

No comments:

Post a Comment