Format File Size as Mb, Gb, etc

Format file size as MB, GB, etc

public static String readableFileSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

This will work up to 1000 TB.... and the program is short!

How can we get the formated file size in KB, MB, GB, TB in R?

I have found various solutions in other programming languages. But this post has a solution suggested by @Rohit Jain which is working fine. With small tweaks implemented it in an R function:


file_size_formated <- function(size){

k = size/1024.0 ^ 1
m = size/1024.0 ^ 2
g = size/1024.0 ^ 3
t = size/1024.0 ^ 4

if (t > 1) {
outSize = paste0(round(t,2),"TB")
} else if (g > 1) {
outSize = paste0(round(g,2),"GB")
} else if (m > 1) {
outSize = paste0(round(m,2),"MB")
} else if (k > 1) {
outSize = paste0(round(k,2),"KB")
} else{
outSize = paste0(round(size,2),"B")
}

return(outSize)
}

Let's say you want to get file sizes for all the files in "www" folder on your device:

# Normal output
file.size(list.files("www",full.names = TRUE))

[1] 255 307 856 1205 1038 5940 250 3940 328 1593 53938 59061210 3750711 16251 42756
[16] 6709 19697 13230426

# Function Output

sapply(file.size(list.files("www",full.names = TRUE)),file_size_formated)

[1] "255B" "307B" "856B" "1.18KB" "1.01KB" "5.8KB" "250B" "3.85KB" "328B" "1.56KB" "52.67KB" "56.33MB" "3.58MB" "15.87KB"
[15] "41.75KB" "6.55KB" "19.24KB" "12.62MB"

Format bytes to kilobytes, megabytes, gigabytes

function formatBytes($bytes, $precision = 2) { 
$units = array('B', 'KB', 'MB', 'GB', 'TB');

$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);

// Uncomment one of the following alternatives
// $bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));

return round($bytes, $precision) . ' ' . $units[$pow];
}

(Taken from php.net, there are many other examples there, but I like this one best :-)

Correct way to convert size in bytes to KB, MB, GB in JavaScript

From this: (source)


Unminified and ES6'ed: (by the community)

function formatBytes(bytes, decimals = 2) {
if (!+bytes) return '0 Bytes'

const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

const i = Math.floor(Math.log(bytes) / Math.log(k))

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}

// Demo code
document.body.innerHTML += `<input type="text" oninput="document.querySelector('p').innerHTML=formatBytes(this.value)" value="1000"><p>1000 Bytes</p>`

How can I convert byte size into a human-readable format in Java?

Fun fact: The original snippet posted here was the most copied Java snippet of all time on Stack Overflow, and it was flawed. It was fixed, but it got messy.

Full story in this article: The most copied Stack Overflow snippet of all time is flawed!

Source: Formatting byte size to human readable format | Programming.Guide

SI (1 k = 1,000)

public static String humanReadableByteCountSI(long bytes) {
if (-1000 < bytes && bytes < 1000) {
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}

Binary (1 Ki = 1,024)

public static String humanReadableByteCountBin(long bytes) {
long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
if (absB < 1024) {
return bytes + " B";
}
long value = absB;
CharacterIterator ci = new StringCharacterIterator("KMGTPE");
for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
value >>= 10;
ci.next();
}
value *= Long.signum(bytes);
return String.format("%.1f %ciB", value / 1024.0, ci.current());
}

Example output:

                             SI     BINARY

0: 0 B 0 B
27: 27 B 27 B
999: 999 B 999 B
1000: 1.0 kB 1000 B
1023: 1.0 kB 1023 B
1024: 1.0 kB 1.0 KiB
1728: 1.7 kB 1.7 KiB
110592: 110.6 kB 108.0 KiB
7077888: 7.1 MB 6.8 MiB
452984832: 453.0 MB 432.0 MiB
28991029248: 29.0 GB 27.0 GiB
1855425871872: 1.9 TB 1.7 TiB
9223372036854775807: 9.2 EB 8.0 EiB (Long.MAX_VALUE)

How do I quickly convert the size element of file.info() from bytes to KB, MB, GB, etc.?

The object.size() function does this type of formatting for it's results, but its meant to tell you the size of the R object you pass to it. It is not set up to take an arbitrary by value.

However, we can "steal" some of it's formatting logic. You can call it with

utils:::format.object_size(60963, "auto")
# [1] "59.5 Kb"

In that way we can call the un-exported formatting function. You can bring up the additional formatting options on the ?format.object_size help page. Note that it uses the rule that 1 Kb = 1024 bytes (not 1000 as in your example).

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is a fairly concise way to do this:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }
if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

// mag is 0 for bytes, 1 for KB, 2, for MB, etc.
int mag = (int)Math.Log(value, 1024);

// 1L << (mag * 10) == 2 ^ (10 * mag)
// [i.e. the number of bytes in the unit corresponding to mag]
decimal adjustedSize = (decimal)value / (1L << (mag * 10));

// make adjustment when the value is large enough that
// it would round up to 1000 or more
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}

return string.Format("{0:n" + decimalPlaces + "} {1}",
adjustedSize,
SizeSuffixes[mag]);
}

And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }

int i = 0;
decimal dValue = (decimal)value;
while (Math.Round(dValue, decimalPlaces) >= 1000)
{
dValue /= 1024;
i++;
}

return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

One thing to bear in mind - in SI notation, "kilo" usually uses a lowercase k while all of the larger units use a capital letter. Windows uses KB, MB, GB, so I have used KB above, but you may consider kB instead.

How do I get a human-readable file size in bytes abbreviation using .NET?

This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
order++;
len = len/1024;
}

// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);

How can I format bytes a cell in Excel as KB, MB, GB etc?

You can't really do calculations in the formatting features of Excel. You can use something like the following to do a rough estimation though:

[<500000]#,##0" B";[<500000000]#,##0,," MB";#,##0,,," GB"


Related Topics



Leave a reply



Submit