More test cases for human readable bytes

pull/6/head
Mark McDowall 10 years ago
parent e715275657
commit c10f02e0b1

@ -7,10 +7,14 @@ namespace NzbDrone.Common.Test.ExtensionTests
[TestFixture]
public class Int64ExtensionFixture
{
[TestCase(0, "0 B")]
[TestCase(1000, "1.0 KB")]
[TestCase(1000000, "1.0 MB")]
[TestCase(377487360, "377.5 MB")]
[TestCase(1255864686, "1.3 GB")]
[TestCase(-1000000, "-1.0 MB")]
[TestCase(-377487360, "-377.5 MB")]
[TestCase(-1255864686, "-1.3 GB")]
public void should_calculate_string_correctly(long bytes, string expected)
{
bytes.SizeSuffix().Should().Be(expected);

@ -4,17 +4,17 @@ namespace NzbDrone.Common.Extensions
{
public static class Int64Extensions
{
private static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
private static readonly string[] SizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
public static string SizeSuffix(this Int64 value)
public static string SizeSuffix(this Int64 bytes)
{
const int bytesInKb = 1000;
if (value < 0) return "-" + SizeSuffix(-value);
if (value == 0) return "0 bytes";
var mag = (int)Math.Log(value, bytesInKb);
var adjustedSize = value / (decimal)Math.Pow(bytesInKb, mag);
if (bytes < 0) return "-" + SizeSuffix(-bytes);
if (bytes == 0) return "0 B";
var mag = (int)Math.Log(bytes, bytesInKb);
var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag);
return string.Format("{0:n1} {1}", adjustedSize, SizeSuffixes[mag]);
}

Loading…
Cancel
Save