Decimal类型截取保留N位小数向上取, Decimal类型截取保留N位小数并且不进行四舍五入操作
2024-08-26 00:20:20
Decimal类型截取保留N位小数向上取
Decimal类型截取保留N位小数并且不进行四舍五入操作
封装静态方法
public class DecimalHelper
{
/// <summary>
/// Decimal类型截取保留N位小数并且不进行四舍五入操作
/// </summary>
/// <param name="d"></param>
/// <param name="n"></param>
/// <returns></returns>
public static decimal CutDecimalWithN(decimal d, int n)
{
string strDecimal = d.ToString();
int index = strDecimal.IndexOf(".");
if (index == -1 || strDecimal.Length < index + n + 1)
{
strDecimal = string.Format("{0:F" + n + "}", d);
}
else
{
int length = index;
if (n != 0)
{
length = index + n + 1;
}
strDecimal = strDecimal.Substring(0, length);
}
return Decimal.Parse(strDecimal);
} /// <summary>
/// Decimal类型截取保留N位小数向上取
/// </summary>
/// <param name="d"></param>
/// <param name="n"></param>
/// <returns></returns>
public static decimal Ceiling(decimal d, int n)
{
decimal t = decimal.Parse(Math.Pow(10, n).ToString());
d = Math.Ceiling(t * d);
return d / t;
}
}
测试方法:
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
decimal Dec = 12.12345M;
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"{Dec} 保留{i} 位小数不进行四舍五入操作:" + DecimalHelper.CutDecimalWithN(Dec, i));
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"{Dec} 保留{i} 位小数向上取整操作:" + DecimalHelper.Ceiling(Dec, i));
}
Console.Read();
}
}
最新文章
- 关于java中多态的理解
- nginx 配置虚拟主机
- 北工大耿丹学院16级计科院3班C语言课程助教学期总结
- ORACLE-树状数据结构获取各层级节点信息
- 怎么添加项目到SVN上面
- iOS开发基础:最新的APP打包上架流程
- jenkins定位GitLab推送的最新Webhook中push event来自哪一个分支
- 配置ADB到Windows环境变量
- 如何用Fiddler手机抓包
- thymleaf模板截取日期的年月日,去掉时分秒
- post方式接口测试(二)_参数化
- centOS7环境下安装jdk1.8
- SqlServer中 将某个表的某个字段改个默认值
- [转]MySQL-5.7 Update语句详解
- classification report 使用
- [原] Bash Script 显示其自身位置
- 解决Anaconda4.2 Navigator打不开的问题
- unity c# script error CS0664: Literal of type double cannot be implicitly converted to type `float&#39;. Add suffix `f&#39; to create a literal of this type
- JavaScript之搜索框
- Web页面中两个listbox的option的转移
热门文章
- Python之路(第二十四篇) 面向对象初级:多态、封装
- [Spark]What&#39;s the difference between spark.sql.shuffle.partitions and spark.default.parallelism?
- Squares of a Sorted Array LT977
- jvm相关知识点
- create a plugin for PowerShell ISE
- C语言基础第五次作业
- 使用xtrabackup备份innodb引擎的数据库
- oracle 查看表行数所占空间大小
- 2018.11.04 洛谷P1081 开车旅行(倍增)
- Educational Codeforces Round 53 (Rated for Div. 2) E. Segment Sum