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

后端 未结 5 555
粉色の甜心
粉色の甜心 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 09:07

    Something like that ?

        public decimal SpecialRound(decimal value) 
        {
            int posDot = value.ToString().IndexOf('.'); // Maybe use something about cultural (in Fr it's ",")
            if(posDot == -1)
                return value;
    
            int posFirstNumber = value.ToString().IndexOfAny(new char[9] {'1', '2', '3', '4', '5', '6', '7', '8', '9'}, posDot);
    
            return Math.Round(value, posFirstNumber);
        }
    

提交回复
热议问题