本文主要介绍.NET(C#)中,小数点后面零的个数不确定,将小数点后第一个非零小数后面的数四舍五入,保留一位小数的方法。

1、示例实现的效果

0.001 -> 0.001
0.00367 -> 0.004
0.00337 -> 0.003
0.000000564 -> 0.0000006
0.00000432907543029 ->  0.000004

2、使用Math.Round()实现代码 

precision变量是Math.Round第二个参数。通过乘10判断小数位数,代码如下:

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

方法可以封装成扩展方法

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);
    }
}

扩展方法调用

decimal input = 0.00001;
input.RoundFirstSignificantDigit();

输出结果

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