Converting KB to MB, GB, TB dynamically

后端 未结 10 1977
广开言路
广开言路 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 19:13

    You are performing integer division. So the result of division is also integer. And fractional part is truncated.

    so, 1245 / 1024 = 1
    

    Change your division to floating point division: -

    double m = size/1024.0;
    double g = size/1048576.0;
    double t = size/1073741824.0;
    

    Also, your comparison is faulty. You should do the comparison with 1.

    if (m > 1), if (t > 1), if (g > 1)
    

    Ideally I would change your comparison to: -

        if (t > 1) {
            hrSize = dec.format(t).concat("TB");
        } else if (g > 1) {
            hrSize = dec.format(g).concat("GB");
        } else if (m > 1) {
            hrSize = dec.format(m).concat("MB");
        } else {
            hrSize = dec.format(size).concat("KB");
        }
    

    You need to compare with the higher unit first, and then move to the lower one.

提交回复
热议问题