From 71c90c49b36965ae43d2cafcfbe713879b38635c Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Tue, 26 Dec 2023 15:56:45 -0600 Subject: [PATCH] Merge handle negatives for ToByteString (#157) * handle negative byteCounts * negatives --- src/chia-dotnet/Extensions.cs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/chia-dotnet/Extensions.cs b/src/chia-dotnet/Extensions.cs index a55302f..11f50e0 100644 --- a/src/chia-dotnet/Extensions.cs +++ b/src/chia-dotnet/Extensions.cs @@ -171,7 +171,7 @@ public static string ToBytesString(this uint byteCount, string format = "N3") /// A human readable string public static string ToBytesString(this int byteCount, string format = "N3") { - return ((ulong)byteCount).ToBytesString(format); + return ((long)byteCount).ToBytesString(format); } /// @@ -182,7 +182,17 @@ public static string ToBytesString(this int byteCount, string format = "N3") /// A human readable string 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]}"; } /// @@ -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]}"; }