Last active
June 4, 2020 14:44
-
-
Save AlbertoMonteiro/a0b46b23e37be16bd971 to your computer and use it in GitHub Desktop.
FileSize em C# e JavaScript
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 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))); | |
| } |
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
| 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