This repository has been archived by the owner on Feb 14, 2024. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Helpers): A function that converts a long into a human readable …
…file-size string.
- Loading branch information
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
namespace Orchard.Tools.Helpers.Long { | ||
using System; | ||
using System.Collections.Generic; | ||
|
||
public static class LongExtensions { | ||
// Should be good enough for now. Will be fun reading this comment in 20 years ;) | ||
private static readonly List<string> units = new List<string>(5) { "B", "KB", "MB", "GB", "TB" }; | ||
|
||
public static string ToHumanReadableString(this long bytes) { | ||
var sizeAndUnit = ConvertToNextUnit(bytes, units[0]); | ||
var numberOfDecimalPlaces = units[0] == sizeAndUnit.Item2 ? 0 : units.IndexOf(sizeAndUnit.Item2) - 1; | ||
return string.Format("{0} {1}", Math.Round(sizeAndUnit.Item1, numberOfDecimalPlaces), sizeAndUnit.Item2); | ||
} | ||
|
||
private static Tuple<double, string> ConvertToNextUnit(double size, string unit) { | ||
var indexOfUnit = units.IndexOf(unit); | ||
|
||
if ( size > 1024 && indexOfUnit < units.Count - 1 ) { | ||
size = size / 1024; | ||
unit = units[indexOfUnit + 1]; | ||
return ConvertToNextUnit(size, unit); | ||
} | ||
|
||
return new Tuple<double, string>(size, unit); | ||
} | ||
} | ||
} |
This file contains 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