Round a decimal number to the first decimal position that is not zero

后端 未结 5 599
粉色の甜心
粉色の甜心 2021-01-17 08:19

I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded.

Examples:

0.001 -> 0.001
0.00367 -&g         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-17 08:53

    I would declare precision variable and use a iteration multiplies that variable by 10 with the original value it didn't hit, that precision will add 1.

    then use precision variable be Math.Round second parameter.

    static decimal RoundFirstSignificantDigit(decimal input) {
        int precision = 0;
        var val = input;
        while (Math.Abs(val) < 1)
        {
            val *= 10;
            precision++;
        }
        return Math.Round(input, precision);
    }
    

    I would write an extension method for this function.

    public static class FloatExtension
    {
        public static decimal RoundFirstSignificantDigit(this decimal input)
        {
            int precision = 0;
            var val = input;
            while (Math.Abs(val) < 1)
            {
                val *= 10;
                precision++;
            }
            return Math.Round(input, precision);
        }
    }
    

    then use like

    decimal input = 0.00001;
    input.RoundFirstSignificantDigit();
    

    c# online

    Result

    (-0.001m).RoundFirstSignificantDigit()                  -0.001
    (-0.00367m).RoundFirstSignificantDigit()                -0.004
    (0.000000564m).RoundFirstSignificantDigit()             0.0000006
    (0.00000432907543029m).RoundFirstSignificantDigit()     0.000004
    

提交回复
热议问题