Math.Ceiling方法向上取整
- 用于对指定的双精度浮点值进行向上取整。这意味着它会返回大于或等于指定数字的最小整数。如果数字是整数,则Math.Ceiling将返回该整数本身。
csharp
double number1 = 3.13;
double number2 = 5.0;
double number3 = -2.72;
double result1 = Math.Ceiling(number1);
double result2 = Math.Ceiling(number2);
double result3 = Math.Ceiling(number3);
// 输出:result1= Ceiling of 3.13 is 4
// 输出:result2 = Ceiling of 5 is 5
// 输出:result3 = Ceiling of -2.72 is -2
- 如果向上取整并想保留特定数量的小数点呢?那么需要先乘以 10的n次方,n 代表保留几位小数,如下
csharp
//要保留1位小数
double number1 = 3.13;
//要保留2位小数
double number2 = 4.357;
//要保留2位小数
double number3 = -7.337;
double result1 = Math.Ceiling(number1 * Math.Pow(10, 1)) / 10;
double result2 = Math.Ceiling(number2 * Math.Pow(10, 2)) / 10 /10;
double result3 = Math.Ceiling(number3 * Math.Pow(10, 2)) / Math.Pow(10, 2);
// 输出:result1= 3.2
// 输出:result2 = 4.36
// 输出:result3 = -7.33
Math.Floor方法向下取整,与上面的正好相反
csharp
double number1 = 3.13;
double number2 = 5.0;
double number3 = -2.72;
double result1 = Math.Floor(number1);
double result2 = Math.Floor(number2);
double result3 = Math.Floor(number3);
//输出: result1 = 3
//输出: result2 = 5
//输出: result3 = -3
以及保留小数点数
csharp
//要保留1位小数
double number1 = 3.13;
//要保留2位小数
double number2 = 4.357;
//要保留2位小数
double number3 = -7.337;
double result1 = Math.Floor(number1 * Math.Pow(10, 1)) / 10;
double result2 = Math.Floor(number2 * Math.Pow(10, 2)) / 10 / 10;
double result3 = Math.Floor(number3 * Math.Pow(10, 2)) / Math.Pow(10, 2);
// 输出:result1= 3.1
// 输出:result2 = 4.35
// 输出:result3 = -7.34