Last active
September 28, 2024 17:58
-
-
Save SatyaSnehith/2441b85c8f945f2cf024fb7e6971d869 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
public class Converter{ | |
static long kilo = 1024; | |
static long mega = kilo * kilo; | |
static long giga = mega * kilo; | |
static long tera = giga * kilo; | |
public static void main(String[] args) { | |
for (String arg: args) { | |
try { | |
System.out.println(getSize(Long.parseLong(arg))); | |
} catch(NumberFormatException e) { | |
System.out.println(arg + " is not a long"); | |
} | |
} | |
} | |
public static String getSize(long size) { | |
String s = ""; | |
double kb = (double)size / kilo; | |
double mb = kb / kilo; | |
double gb = mb / kilo; | |
double tb = gb / kilo; | |
if(size < kilo) { | |
s = size + " Bytes"; | |
} else if(size >= kilo && size < mega) { | |
s = String.format("%.2f", kb) + " KB"; | |
} else if(size >= mega && size < giga) { | |
s = String.format("%.2f", mb) + " MB"; | |
} else if(size >= giga && size < tera) { | |
s = String.format("%.2f", gb) + " GB"; | |
} else if(size >= tera) { | |
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
@Cranked Nice and clean ... but expensive! Do NOT use in (tight) loops.
Mixed alternative: