Skip to content

Commit

Permalink
Fix floating point rounding error in FormatTime
Browse files Browse the repository at this point in the history
  • Loading branch information
UncraftedName committed Oct 18, 2024
1 parent 5bc55d1 commit b8beaee
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions ConsoleApp/src/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}";
}


Expand Down

0 comments on commit b8beaee

Please sign in to comment.