From b8beaee6d8d81fc8b8ead9672bebe9c38bf00966 Mon Sep 17 00:00:00 2001 From: UncraftedName Date: Fri, 18 Oct 2024 04:50:05 -0700 Subject: [PATCH] Fix floating point rounding error in FormatTime --- ConsoleApp/src/Utils.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ConsoleApp/src/Utils.cs b/ConsoleApp/src/Utils.cs index a482c77..aeb684c 100644 --- a/ConsoleApp/src/Utils.cs +++ b/ConsoleApp/src/Utils.cs @@ -92,17 +92,15 @@ public static string FormatTime(double seconds) { if (Math.Abs(seconds) > 8640000) // 10 days, probably happens from initializing the tick interval to garbage return "invalid"; string sign = seconds < 0 ? "-" : ""; - // timespan truncates values, (makes sense since 0.5 minutes is still 0 total minutes) so I round manually - TimeSpan t = TimeSpan.FromSeconds(Math.Abs(seconds)); - int roundedMilli = t.Milliseconds + (int)Math.Round(t.TotalMilliseconds - (long)t.TotalMilliseconds); + TimeSpan t = TimeSpan.FromSeconds(Math.Round(Math.Abs(seconds), 3)); if (t.Days > 0) - return $"{sign}{t.Days:D1}.{t.Hours:D2}:{t.Minutes:D2}:{t.Seconds:D2}.{roundedMilli:D3}"; + return $"{sign}{t.Days:D1}.{t.Hours:D2}:{t.Minutes:D2}:{t.Seconds:D2}.{t.Milliseconds:D3}"; else if (t.Hours > 0) - return $"{sign}{t.Hours:D1}:{t.Minutes:D2}:{t.Seconds:D2}.{roundedMilli:D3}"; + return $"{sign}{t.Hours:D1}:{t.Minutes:D2}:{t.Seconds:D2}.{t.Milliseconds:D3}"; else if (t.Minutes > 0) - return $"{sign}{t.Minutes:D1}:{t.Seconds:D2}.{roundedMilli:D3}"; + return $"{sign}{t.Minutes:D1}:{t.Seconds:D2}.{t.Milliseconds:D3}"; else - return $"{sign}{t.Seconds:D1}.{roundedMilli:D3}"; + return $"{sign}{t.Seconds:D1}.{t.Milliseconds:D3}"; }