fix: math round methods not working properly

This commit is contained in:
2025-10-16 15:37:03 +03:00
parent 6f1f30bd53
commit b75f30f864
2 changed files with 21 additions and 9 deletions

View File

@@ -240,21 +240,33 @@ public static class Math
public static T Lerp<T>(T x, T y, T t) where T : IFloatingPoint<T> => x + (y - x) * t;
/// <summary>
/// Rounds a number to a specified number of fractional digits.
/// Rounds a number to the closest integer.
/// </summary>
/// <param name="x">The number to round.</param>
/// <param name="digits">The number of fractional digits in the return value.</param>
/// <param name="mode">Specification for how to round <paramref name="x"/> if it is midway between two other numbers.</param>
/// <returns>The number <paramref name="x"/> rounded to <paramref name="digits"/> fractional digits.</returns>
public static float Round(float x, int digits, MidpointRounding mode) => MathF.Round(x, digits, mode);
/// <param name="roundMode">Specification for how to round <paramref name="x"/> if it is midway between two other numbers.</param>
/// <returns>The number <paramref name="x"/> rounded to the closest integer.</returns>
public static float Round(float x, RoundMode roundMode) => RoundToInt(x, roundMode);
/// <summary>
/// Rounds a number to an integer.
/// Rounds a number to the closest integer.
/// </summary>
/// <param name="x">The number to round.</param>
/// <param name="roundMode">Specification for how to round <paramref name="x"/> if it's midway between two numbers</param>
/// <returns></returns>
public static int RoundToInt(float x, RoundMode roundMode = RoundMode.Ceil) => (int)MathF.Round(x, 0, roundMode == RoundMode.Ceil ? MidpointRounding.ToPositiveInfinity : MidpointRounding.ToNegativeInfinity);
/// <returns>The number <paramref name="x"/> rounded to the closest integer.</returns>
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 };
/// <summary>

View File

@@ -81,7 +81,7 @@ public static class MathExtensions
public static T Lerp<T>(this T x, T y, T t) where T : IFloatingPoint<T> => Math.Lerp(x, y, t);
/// <inheritdoc cref="Math.Round(float, int, MidpointRounding)" />
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);
/// <inheritdoc cref="Math.RoundToInt(float, Math.RoundMode)" />
public static int RoundToInt(this float x, Math.RoundMode roundMode = Math.RoundMode.Ceil) => Math.RoundToInt(x, roundMode);