Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting KB to MB, GB, TB dynamically

public String size(int size){
    String hrSize = "";
    int k = size;
    double m = size/1024;
    double g = size/1048576;
    double t = size/1073741824;

    DecimalFormat dec = new DecimalFormat("0.00");

    if (k>0)
    {

        hrSize = dec.format(k).concat("KB");

    }
    if (m>0)
    {

        hrSize = dec.format(m).concat("MB");
    }
    if (g>0)
    {

        hrSize = dec.format(g).concat("GB");
    }
    if (t>0)
    {

        hrSize = dec.format(t).concat("TB");
    }

    return hrSize;
    }

This is a method that should return size in GB,MB, KB or TB. Input value is in KB. for example result for 1245 should be like 1.21MB but what I get is 1.00MB.

like image 809
pedja Avatar asked Nov 24 '12 09:11

pedja


People also ask

What are the relationship between KB MB GB and TB?

A kilobyte (KB) is 1,000 bytes, and one megabyte (MB) is 1,000 kilobytes. One gigabyte (GB) is equal to 1,000 megabytes, while a terabyte (TB) is 1,000 gigabytes.

How do I convert a KB file to MB?

How to convert KiloBytes to MegaBytes? To convert between KB and MB you need to divide by 1000 if using the SI convention and by 1024 if using the binary convention.


2 Answers

A modified version. Only calls format once. Includes "Bytes".

public static 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 dec = new DecimalFormat("0.00");

    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 if ( k>1 ) {
        hrSize = dec.format(k).concat(" KB");
    } else {
        hrSize = dec.format(b).concat(" Bytes");
    }

    return hrSize;
}
like image 157
bickster Avatar answered Sep 21 '22 23:09

bickster


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.

like image 38
Rohit Jain Avatar answered Sep 20 '22 23:09

Rohit Jain