How to convert bytes to KB or MB or GB or TB or PB in Java

1 Answer

0 votes
public class MyClass {
    private static String convert_bytes(long bytes) {
        String sizes[] = { "B", "KB", "MB", "GB", "TB", "PB" };
        double dbytes = bytes;
         
        int i = 0;
        while (i < sizes.length && bytes >= 1024) {
             dbytes = bytes / 1024.0;
             i++;     
             bytes /= 1024;
        }
 
        return String.format("%.2f %s", dbytes, sizes[i]);
    }
    public static void main(String args[]) {
        System.out.println(convert_bytes(554432));
        System.out.println(convert_bytes(3554432));
        System.out.println(convert_bytes(33554432));
        System.out.println(convert_bytes(333554432));
        System.out.println(convert_bytes(3333554432L));
        System.out.println(convert_bytes(33333554432L));
        System.out.println(convert_bytes(333333554432L));
        System.out.println(convert_bytes(3333333554432L));
        System.out.println(convert_bytes(33333333554432L));
        System.out.println(convert_bytes(333333333554432L));
        System.out.println(convert_bytes(3333333333554432L));
    }
}
 
 
 
 
/*
run:
 
541.44 KB
3.39 MB
32.00 MB
318.10 MB
3.10 GB
31.04 GB
310.44 GB
3.03 TB
30.32 TB
303.16 TB
2.96 PB
 
*/

 



answered Nov 5, 2021 by avibootz
edited Nov 5, 2021 by avibootz
...