C# Math.Ceiling方法向上取整和Math.Floor方法向下取整

Math.Ceiling方法向上取整

  1. 用于对指定的双精度浮点值进行向上取整。这意味着它会返回大于或等于指定数字的最小整数。如果数字是整数,则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  
  1. 如果向上取整并想保留特定数量的小数点呢?那么需要先乘以 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  
相关推荐
程序设计实验室2 小时前
C# 扩展方法只会写 this 吗?C# 14 新语法直接把扩展方法玩出了花
c#
唐青枫4 小时前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
c#·.net
唐宋元明清218810 小时前
.NET Win32磁盘动态卷/跨区卷触发“函数不正确”问题排查
windows·c#·存储
hez201011 小时前
Satori GC:同时做到高吞吐、低延时和低内存占用
c#·.net·.net core·gc·clr
唐青枫1 天前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
c#·.net
小峥降临2 天前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
晨星shine6 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530146 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526746 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526746 天前
接口文档汇总 - 3.PLC通信管理
c#