Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

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
...