没有精度的四舍五入小数

Rounding Decimal with no precision

我想将这个小数 14999994 四舍五入到这个值 15000000,但是 Math.Round() 对我不起作用!

请注意我的十进制数没有任何精度

static double RoundToSignificantDigits(double d, int digits)
{
    if (d == 0)
    {
        return 0;
    }

    double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);
    return Math.Sign(d) * scale * Math.Ceiling(Math.Abs(d) / scale);
}

它基于Math.Log10计算"scale"(但请注意Math.Abs为负数!),减去给定的数字精度,然后将数字除以this "scale",四舍五入并乘以 this "scale"。请注意 Math.Sign 的用法:我们四舍五入 (Math.Ceiling) d 的绝对值,然后 "reattach" 符号。

像这样使用它:

double n = RoundToSignificantDigits(14999994, 2); // 15000000 

请注意 double 是一只丑陋的野兽:

double num = 0.2;
num += 0.1; // 0.30000000000000004

double num2 = RoundToSignificantDigits(num, 1); // 0.4