VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之Decimal类型截取保留N位小数向上取, Deci

Decimal类型截取保留N位小数向上取
Decimal类型截取保留N位小数并且不进行四舍五入操作

封装静态方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
    }
}