向上取整Math.Ceiling的用法
1.向上取整Math.Ceiling 方法
Math.Ceiling 方法用于对指定的双精度浮点值进行向上取整。这意味着它会返回大于或等于指定数字的最小整数。如果数字是整数,则Math.Ceiling将返回该整数本身。 |
---|
C#代码
using System;
class Program
{
static void Main()
{
double number1 = 3.14;
double number2 = 5.0;
double number3 = -2.71;
double result1 = Math.Ceiling(number1);
double result2 = Math.Ceiling(number2);
double result3 = Math.Ceiling(number3);
// 输出:result1= Ceiling of 3.14 is 4
// 输出:result2 = Ceiling of 5 is 5
// 输出:result3 = Ceiling of -2.71 is -2
}
}
2.我要向上取整并保留特定数量的小数点呢?
如果你想保留特定数量的小数点,你需要先将数字乘以10的相应次方,然后向上舍入,最后再除以相同的值。 |
---|
例如,如果你想要保留一位小数
VB.net代码
Dim number As Double = 10.34
Dim decimalPlaces As Integer = 1
Dim factor As Double = Math.Pow(10, decimalPlaces)
Dim roundedUp As Double = Math.Ceiling(number * factor) / factor
Console.WriteLine(roundedUp) ' 输出 10.4
3.例子