public static class NumberHelper { public static bool DoubleHasValue(double? value, double maxDiff = double.Epsilon) => Math.Abs(value.GetValueOrDefault(0.0)) > maxDiff; public static string InvariantToString(double? value) => value.GetValueOrDefault(0.0).ToString(CultureInfo.InvariantCulture); public static bool IsAlmostZero(double d) => Math.Abs(d) < 0.0000001; public static bool IsEqualTo(double a, double b, double maxDiff = double.Epsilon) => Math.Abs(b - a) <= maxDiff; public static double DivideSafe(double input, double divideBy) => IsEqualTo(0.0, divideBy) ? input : input / divideBy; public static double SafeCalculatePercentage(double share, double whole) => IsEqualTo(whole, 0.0) ? 100 : share / whole * 100; public static int DoubleToIntCeiling(double d) => (int)Math.Ceiling(d); public static double GetPercentageDifference(double expected, double current) => Math.Abs((current - expected) / expected * 100); public static double GetPercentage(double whole, double part) => Math.Abs(part / whole * 100); public static bool IsNumeric(object o) => o is byte || o is sbyte || o is ushort || o is uint || o is ulong || o is short || o is int || o is long || o is float || o is double || o is decimal; public static double Limit(double val, double min, double max) => Math.Max(min, Math.Min(max, val)); public static double Map(double val, double inMin, double inMax, double outMin, double outMax) => (Limit(val, inMin, inMax) - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; public static double RoundNumberUpBy(double number, double roundBy) => Math.Ceiling(number * 1.0 / roundBy) * roundBy; // Only add up public static double RoundNumberBy(double number, double roundBy) => Math.Round(number * 1.0 / roundBy) * roundBy; public static double? GetDoubleFromString(string s, double? def = null) { if (double.TryParse(s, NumberStyles.Float | NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) return result; return def; } public static int? GetIntFromDoubleRounded(double? d, int? def = null) { if (d == null) return def; return (int)Math.Round(d.Value); } public static long GetLongFromString(string input, long def = default) { if (string.IsNullOrWhiteSpace(input)) return def; if (long.TryParse(input, out var l)) return l; return def; } public static double ToDouble(object o, double def = default) { if (o == null) return def; if (o is double d1) return d1; var str = Convert.ToString(o, CultureInfo.InvariantCulture); if (double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out var d)) return d; return def; } }
638700cookie-checkC# NumberHelper