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

后端 未结 5 598
粉色の甜心
粉色の甜心 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:49

    Another approach

        decimal RoundToFirstNonNullDecimal(decimal value)
        {
            var nullDecimals = value.ToString().Split('.').LastOrDefault()?.TakeWhile(c => c == '0').Count();
            var roundTo = nullDecimals.HasValue && nullDecimals >= 1 ? nullDecimals.Value + 1 : 2;
            return Math.Round(value, roundTo);
        }
    

    Result

            Console.WriteLine(RoundToFirstNonNullDecimal(0.001m));                0.001
            Console.WriteLine(RoundToFirstNonNullDecimal(0.00367m));              0.004
            Console.WriteLine(RoundToFirstNonNullDecimal(0.000000564m));          0.0000006
            Console.WriteLine(RoundToFirstNonNullDecimal(0.00000432907543029m));  0.000004
            Console.WriteLine(RoundToFirstNonNullDecimal(0.12m));                 0.12
            Console.WriteLine(RoundToFirstNonNullDecimal(1.232m));                1.23
            Console.WriteLine(RoundToFirstNonNullDecimal(7));                     7.00
    

提交回复
热议问题