Skip to content
This repository has been archived by the owner on Feb 14, 2024. It is now read-only.

Commit

Permalink
feat(Helpers): A function that converts a long into a human readable …
Browse files Browse the repository at this point in the history
…file-size string.
  • Loading branch information
Xceno committed Jul 14, 2018
1 parent 3014a5c commit 0daf3c0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Helpers/Long/LongExtensions.cs
@@ -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);
}
}
}
1 change: 1 addition & 0 deletions Orchard.Tools.csproj
Expand Up @@ -112,6 +112,7 @@
<Compile Include="Commands\CodeGenerationCommands.cs" />
<Compile Include="Commands\TemplateInfo.cs" />
<Compile Include="Helpers\Html\HtmlHelperExtensions.cs" />
<Compile Include="Helpers\Long\LongExtensions.cs" />
<Compile Include="Helpers\Resources\ResourceDefinitionExtensions.cs" />
<Compile Include="Helpers\Resources\ResourceManifestExtensions.cs" />
<Compile Include="Helpers\Strings\StringExtensions.cs" />
Expand Down

0 comments on commit 0daf3c0

Please sign in to comment.