Converting KB to MB, GB, TB dynamically

后端 未结 10 1972
广开言路
广开言路 2020-12-14 18:24
public String size(int size){
    String hrSize = \"\";
    int k = size;
    double m = size/1024;
    double g = size/1048576;
    double t = size/1073741824;

            


        
10条回答
  •  臣服心动
    2020-12-14 19:12

    bickster's answer works quite alright but the problem with it is that it returns results like 45.00 Bytes and 12.00 KB. In my opinion, the last decimal digits should be removed if they are zeros. So instead of 45.00 Bytes and 12.00 KB, you get 45 B and 12 KB (notice that Bytes has been changed to B. This is just for uniformity since we have KB, MB etc and not Kilobytes, Megabytes etc).

    private boolean isDouble(double value) {
            if (value % 1 == 0) {
                Log.d(TAG, "value is " + value + " and is not double");
                return false;
            } else {
                Log.d(TAG, "value is " + value + " and is double");
                return true;
            }
        }
    

    The above method simply checks if the value has zeros as decimal digits.

    private String formatFileSize(long size) {
            String hrSize = null;
            double b = size;
            double k = size/1024.0;
            double m = ((size/1024.0)/1024.0);
            double g = (((size/1024.0)/1024.0)/1024.0);
            double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0);
    
            DecimalFormat dec1 = new DecimalFormat("0.00");
            DecimalFormat dec2 = new DecimalFormat("0");
            if (t>1) {
                hrSize = isDouble(t) ? dec1.format(t).concat(" TB") : dec2.format(t).concat(" TB");
            } else if (g>1) {
                hrSize = isDouble(g) ? dec1.format(g).concat(" GB") : dec2.format(g).concat(" GB");
            } else if (m>1) {
                hrSize = isDouble(m) ? dec1.format(m).concat(" MB") : dec2.format(m).concat(" MB");
            } else if (k>1) {
                hrSize = isDouble(k) ? dec1.format(k).concat(" KB") : dec2.format(k).concat(" KB");
            } else {
                hrSize = isDouble(b) ? dec1.format(b).concat(" B") : dec2.format(b).concat(" B");
            }
            return hrSize;
        }
    

提交回复
热议问题