如何根据小数位数将数字四舍五入到下一个数字?

问题描述 投票:0回答:1

这是我尝试的结果:

396.6 -> 400
39.66 -> 40
3.96 -> 4
0.396 -> 0.4

如何在 C# 中做到这一点? 这是我的尝试:

public static double CeilToNextSameDecimal(double number)
{
    int decimalPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2];
    double factor = Math.Pow(10, decimalPlaces);
    return Math.Ceiling(number * factor) / factor;
}

但是给我错误的结果(即相同的输入):

396.6
39.66
3.966
0.3966
c# math rounding
1个回答
0
投票

这是我的尝试:

var round = Math.Ceiling(input / 10);
var result = input < 1 ?                  
        (Math.Ceiling((d * 10)) / 10) : 
            ? Math.Ceiling((input /10) * 10) 
            : round * 10;

.网络小提琴

© www.soinside.com 2019 - 2024. All rights reserved.