Skip to content

Instantly share code, notes, and snippets.

@markcastle
Created May 25, 2022 11:25
Show Gist options
  • Save markcastle/3da4ac67958442a28cb892938e7d52bf to your computer and use it in GitHub Desktop.
Save markcastle/3da4ac67958442a28cb892938e7d52bf to your computer and use it in GitHub Desktop.
/*
* Some simple Float Extensions
*/
using System;
namespace YOURNAMESPACE.Extensions
{
public static class FloatExtensions
{
/// <summary>
/// Check if floats are the same when compared using the same number of decimal places
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <param name="decimalPlaces"></param>
/// <returns>bool</returns>
public static bool IsEqual(this float first, float second, int decimalPlaces = 3)
{
string dp = new('0', decimalPlaces);
return first.ToString($"0.{dp}") == second.ToString($"0.{dp}");
}
/// <summary>
/// Check if doubles are the same when compared using the same number of decimal places
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <param name="decimalPlaces"></param>
/// <returns>bool</returns>
public static bool IsEqual(this double first, double second, int decimalPlaces = 3)
{
string dp = new('0', decimalPlaces);
return first.ToString($"0.{dp}") == second.ToString($"0.{dp}");
}
/// <summary>
/// Clamp a float to a specific number of places using standard c# rounding
/// </summary>
/// <param name="first"></param>
/// <param name="decimalPlaces"></param>
/// <returns>float</returns>
public static float ClampTo(this float first, int decimalPlaces = 3)
{
return (float)Math.Round(first, 3);
}
/// <summary>
/// Compare two floats
/// tolerance is a double so if you want to compare to 0.0001 then use that.
/// See: https://stackoverflow.com/questions/1530069/comparing-floating-point-values
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="tolerance"></param>
/// <returns>bool</returns>
public static bool IsNearlyEqualTo(this float a, float b, float tolerance)
{
return Math.Abs(a - b) < tolerance;
}
/// <summary>
/// Compare two doubles
/// tolerance is a double so if you want to compare to 0.0001 then use that.
/// See: https://stackoverflow.com/questions/1530069/comparing-floating-point-values
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="tolerance"></param>
/// <returns>bool</returns>
public static bool IsNearlyEqualTo(this double a, double b, double tolerance)
{
return Math.Abs(a - b) < tolerance;
}
/// <summary>
/// Compare two doubles - High precision
/// See: https://stackoverflow.com/questions/1530069/comparing-floating-point-values
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns>bool</returns>
public static bool IsNearlyEqualTo(this double a, double b)
{
return Math.Abs(a - b) < double.Epsilon;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment