Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Last active June 4, 2020 14:44
Show Gist options
  • Select an option

  • Save AlbertoMonteiro/a0b46b23e37be16bd971 to your computer and use it in GitHub Desktop.

Select an option

Save AlbertoMonteiro/a0b46b23e37be16bd971 to your computer and use it in GitHub Desktop.
FileSize em C# e JavaScript
public static class LongExtensions
{
private static readonly string[] Sizes = { "bytes", "KB", "MB", "GB", "TB" };
public static string ToFileSize(this long? bytesSize) => bytesSize.HasValue ? ToFileSize(bytesSize.Value) : "0 bytes";
public static string ToFileSize(this long bytesSize) => SizeWithMaxSize.TakeWhile(e => bytesSize >= e.Item2).Select(size=> $"{bytesSize / size.Item2:0.#} {size.Item1}").Last();
private static IEnumerable<Tuple<string, double>> SizeWithMaxSize => Sizes.Select((s, i) => new Tuple<string, double>(s, Pow(1024, i)));
}
function toFileSize(bytesSize) {
bytesSize = isNaN(bytesSize) ? 0 : bytesSize;
var oneByte = 1;
var kiloByte = oneByte * 1024;
var megaByte = kiloByte * 1024;
var gigaByte = megaByte * 1024;
var teraByte = gigaByte * 1024;
var size, unit;
if (bytesSize >= teraByte) {
size = Math.round(bytesSize / teraByte, 1);
unit = 'TB';
} else if (bytesSize >= gigaByte) {
size = bytesSize / gigaByte;
unit = 'GB';
} else if (bytesSize >= megaByte) {
size = bytesSize / megaByte;
unit = 'MB';
} else if (bytesSize >= kiloByte) {
size = bytesSize / kiloByte;
unit = 'KB';
} else {
size = bytesSize / oneByte;
unit = 'bytes';
}
size = Math.round(size * 100) / 100;
return size + ' ' + unit;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment