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

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

    var value = 0.000000564;
    
    int cnt = 0;
    bool hitNum = false;
    var tempVal = value;
    while (!hitNum)
    {
        if(tempVal > 1)
        {
            hitNum = true;
        }
        else
        {
            tempVal *= 10;
            cnt++;
        }
    }
    
    var newValue = (decimal)Math.Round(value, cnt);
    

提交回复
热议问题