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();
}
}

最新文章

  1. 关于java中多态的理解
  2. nginx 配置虚拟主机
  3. 北工大耿丹学院16级计科院3班C语言课程助教学期总结
  4. ORACLE-树状数据结构获取各层级节点信息
  5. 怎么添加项目到SVN上面
  6. iOS开发基础:最新的APP打包上架流程
  7. jenkins定位GitLab推送的最新Webhook中push event来自哪一个分支
  8. 配置ADB到Windows环境变量
  9. 如何用Fiddler手机抓包
  10. thymleaf模板截取日期的年月日,去掉时分秒
  11. post方式接口测试(二)_参数化
  12. centOS7环境下安装jdk1.8
  13. SqlServer中 将某个表的某个字段改个默认值
  14. [转]MySQL-5.7 Update语句详解
  15. classification report 使用
  16. [原] Bash Script 显示其自身位置
  17. 解决Anaconda4.2 Navigator打不开的问题
  18. 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
  19. JavaScript之搜索框
  20. Web页面中两个listbox的option的转移

热门文章

  1. Python之路(第二十四篇) 面向对象初级:多态、封装
  2. [Spark]What&#39;s the difference between spark.sql.shuffle.partitions and spark.default.parallelism?
  3. Squares of a Sorted Array LT977
  4. jvm相关知识点
  5. create a plugin for PowerShell ISE
  6. C语言基础第五次作业
  7. 使用xtrabackup备份innodb引擎的数据库
  8. oracle 查看表行数所占空间大小
  9. 2018.11.04 洛谷P1081 开车旅行(倍增)
  10. Educational Codeforces Round 53 (Rated for Div. 2) E. Segment Sum