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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,038 questions

40,803 answers

573 users

How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Java

1 Answer

0 votes
package javaapplication1;

public class Example {
    public static void main(String[] args) {
       
        System.out.println(FormatBytes(9823453784599L));
        System.out.println(FormatBytes(7124362542L));        
        System.out.println(FormatBytes(23746178));        
        System.out.println(FormatBytes(1048576));        
        System.out.println(FormatBytes(1024000));
        System.out.println(FormatBytes(873445));
        System.out.println(FormatBytes(1024));
        System.out.println(FormatBytes(978));
        System.out.println(FormatBytes(13));
        System.out.println(FormatBytes(0));
    }
    private static String FormatBytes(long bytes)
    {
        String[] sizes = { "B", "KB", "MB", "GB", "TB" };

        int i;
        double dblByte = bytes;
        for (i = 0; i < sizes.length && bytes >= 1024; i++, bytes /= 1024)
             dblByte = bytes / 1024.0;

        return String.format("%.2f %s", dblByte, sizes[i]);
    }
}
 
/*
run:
  
8.93 TB
6.63 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0.00 B
  
*/

 





answered Apr 22, 2016 by avibootz
...