From b75f30f864921bb16f4221f66bb97356eafb9a36 Mon Sep 17 00:00:00 2001 From: Syntriax Date: Thu, 16 Oct 2025 15:37:03 +0300 Subject: [PATCH] fix: math round methods not working properly --- Engine.Core/Math.cs | 28 ++++++++++++++++++++-------- Engine.Core/MathExtensions.cs | 2 +- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/Engine.Core/Math.cs b/Engine.Core/Math.cs index a8f939e..b65cc5e 100644 --- a/Engine.Core/Math.cs +++ b/Engine.Core/Math.cs @@ -240,21 +240,33 @@ public static class Math public static T Lerp(T x, T y, T t) where T : IFloatingPoint => x + (y - x) * t; /// - /// Rounds a number to a specified number of fractional digits. + /// Rounds a number to the closest integer. /// /// The number to round. - /// The number of fractional digits in the return value. - /// Specification for how to round if it is midway between two other numbers. - /// The number rounded to fractional digits. - public static float Round(float x, int digits, MidpointRounding mode) => MathF.Round(x, digits, mode); + /// Specification for how to round if it is midway between two other numbers. + /// The number rounded to the closest integer. + public static float Round(float x, RoundMode roundMode) => RoundToInt(x, roundMode); /// - /// Rounds a number to an integer. + /// Rounds a number to the closest integer. /// /// The number to round. /// Specification for how to round if it's midway between two numbers - /// - public static int RoundToInt(float x, RoundMode roundMode = RoundMode.Ceil) => (int)MathF.Round(x, 0, roundMode == RoundMode.Ceil ? MidpointRounding.ToPositiveInfinity : MidpointRounding.ToNegativeInfinity); + /// The number rounded to the closest integer. + public static int RoundToInt(float x, RoundMode roundMode = RoundMode.Ceil) + { + float remainder = x.Mod(1f); + + if (remainder == .5f) + if (roundMode == RoundMode.Floor) + return (int)x; + else + return (int)(x + .5f); + + if (x < 0f) + return (int)(x - .5f); + return (int)(x + .5f); + } public enum RoundMode { Ceil, Floor }; /// diff --git a/Engine.Core/MathExtensions.cs b/Engine.Core/MathExtensions.cs index 63f2dcb..d1fd4aa 100644 --- a/Engine.Core/MathExtensions.cs +++ b/Engine.Core/MathExtensions.cs @@ -81,7 +81,7 @@ public static class MathExtensions public static T Lerp(this T x, T y, T t) where T : IFloatingPoint => Math.Lerp(x, y, t); /// - public static float Round(this float x, int digits, MidpointRounding mode) => Math.Round(x, digits, mode); + public static float Round(this float x, Math.RoundMode mode) => Math.Round(x, mode); /// public static int RoundToInt(this float x, Math.RoundMode roundMode = Math.RoundMode.Ceil) => Math.RoundToInt(x, roundMode);