using DecimalMath;
using static System.Math;
using static DecimalMath.DecimalEx;

namespace InnovEnergy.Lib.Utils;

public static class DecimalUtils
{
    public static Double RoundToSignificantDigits(this Double num, Int32 n)
    {
        if (num == 0)
            return 0;

        var d = Ceiling(Log10(num < 0 ? -num : num));
        var power = n - (Int32)d;

        var magnitude = Math.Pow(10, power);
        var shifted   = Round(num * magnitude);
        
        return shifted / magnitude;
    }
    
    public static Decimal RoundToSignificantDigits(this Decimal num, Int32 n)
    {
        if (num == 0)
            return 0;

        var d = Ceiling(Log10(num < 0 ? -num : num));
        var power = n - (Int32)d;

        var magnitude = DecimalEx.Pow(10, power);
        var shifted   = Round(num * magnitude);
        
        return shifted / magnitude;
    }
}