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  
相关推荐
格林威1 小时前
C# 相机图像阴影校正:使用OpenCvSharp实现工业相机阴影平场校正功能
人工智能·数码相机·opencv·计算机视觉·c#·机器视觉·工业相机
俊昭喜喜里1 小时前
c#中的构造函数
开发语言·数据库·c#
hahaha60161 小时前
HLS高层次综合设计--axi之burst纠偏
开发语言·算法·fpga开发·c#
点心的游戏开发世界10 小时前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
淡海水12 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
点心的游戏开发世界12 小时前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
公子小六16 小时前
基于.NET的Windows窗体编程之WinForms滑块与上下控件
windows·microsoft·c#·.net·winforms
曹牧17 小时前
C#:文本文件读取
服务器·前端·c#
2601_9673387117 小时前
C#上位机开发零基础入门到精通全套视频
开发语言·c#
czhc11400756631 天前
2026-09-03 博客:配置与密码 · 合并代码 · 超时排查
c#