-
-
Save praveenb/b346032dd9ae8f4e8080d864355eb7f7 to your computer and use it in GitHub Desktop.
Convert Bytes to KB, MB, GB, TB - java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Converter{ | |
| public static void main(String[] args) { | |
| System.out.println(getSize(1048576)); | |
| } | |
| public static String getSize(long size) { | |
| long n = 1024; | |
| String s = ""; | |
| double kb = size / n; | |
| double mb = kb / n; | |
| double gb = mb / n; | |
| double tb = gb / n; | |
| if(size < n) { | |
| s = size + " Bytes"; | |
| } else if(size >= n && size < (n * n)) { | |
| s = String.format("%.2f", kb) + " KB"; | |
| } else if(size >= (n * n) && size < (n * n * n)) { | |
| s = String.format("%.2f", mb) + " MB"; | |
| } else if(size >= (n * n * n) && size < (n * n * n * n)) { | |
| s = String.format("%.2f", gb) + " GB"; | |
| } else if(size >= (n * n * n * n)) { | |
| s = String.format("%.2f", tb) + " TB"; | |
| } | |
| return s; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment