Converting KB to MB, GB, TB dynamically

后端 未结 10 1971
广开言路
广开言路 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:10

    class ConverterUtils{
        public static void main(String[] args) {
            System.out.println(getSize(1234567));
        }
        public static String getSize(long size) {
            String s = "";
            double kb = size / 1024;
            double mb = kb / 1024;
            double gb = mb / 1024;
            double tb = gb / 1024;
            if(size < 1024L) {
                s = size + " Bytes";
            } else if(size >= 1024 && size < (1024L * 1024)) {
                s =  String.format("%.2f", kb) + " KB";
            } else if(size >= (1024L * 1024) && size < (1024L * 1024 * 1024)) {
                s = String.format("%.2f", mb) + " MB";
            } else if(size >= (1024L * 1024 * 1024) && size < (1024L * 1024 * 1024 * 1024)) {
                s = String.format("%.2f", gb) + " GB";
            } else if(size >= (1024L * 1024 * 1024 * 1024)) {
                s = String.format("%.2f", tb) + " TB";
            }
            return s;
        }
    }
    

    To better understand - https://www.techspot.com/news/68482-quickly-convert-between-storage-size-units-kb-mb.html

提交回复
热议问题