Skip to content

Commit

Permalink
Merge handle negatives for ToByteString (#157)
Browse files Browse the repository at this point in the history
* handle negative byteCounts

* negatives
  • Loading branch information
dkackman authored Dec 26, 2023
1 parent 276ebcf commit 71c90c4
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/chia-dotnet/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public static string ToBytesString(this uint byteCount, string format = "N3")
/// <returns>A human readable string</returns>
public static string ToBytesString(this int byteCount, string format = "N3")
{
return ((ulong)byteCount).ToBytesString(format);
return ((long)byteCount).ToBytesString(format);
}

/// <summary>
Expand All @@ -182,7 +182,17 @@ public static string ToBytesString(this int byteCount, string format = "N3")
/// <returns>A human readable string</returns>
public static string ToBytesString(this long byteCount, string format = "N3")
{
return ((ulong)byteCount).ToBytesString(format);
string[] suffixes = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "YiB" };
if (byteCount == 0)
{
return $"{0.0.ToString(format)} {suffixes[0]}";
}

var abs = Math.Abs(byteCount); // in case byteCount is negative
var place = Convert.ToInt32(Math.Floor(Math.Log(abs, 1024)));
var num = Math.Sign(byteCount) * Math.Round(abs / Math.Pow(1024, place), 1);

return $"{num.ToString(format)} {suffixes[place]}";
}

/// <summary>
Expand All @@ -199,8 +209,9 @@ public static string ToBytesString(this double byteCount, string format = "N3")
return $"{0.0.ToString(format)} {suffixes[0]}";
}

var place = Convert.ToInt32(Math.Floor(Math.Log(byteCount, 1024)));
var num = Math.Round(byteCount / Math.Pow(1024, place), 1);
var abs = Math.Abs(byteCount); // in case byteCount is negative
var place = Convert.ToInt32(Math.Floor(Math.Log(abs, 1024)));
var num = Math.Sign(byteCount) * Math.Round(abs / Math.Pow(1024, place), 1);

return $"{num.ToString(format)} {suffixes[place]}";
}
Expand Down

0 comments on commit 71c90c4

Please sign in to comment.