C#常用小数取整数的示例代码

发布时间:2020-12-20编辑:脚本学堂
分享一例C#中常用的小数取整数的代码,学习下四舍五入、数字截取的方法,有需要的朋友参考下。

本节内容:
c#编程中小数取整。

示例图:
小数取整数

例子:
 

复制代码 代码示例:
 public class DoubleCovertToInt小数取整
    {
        public void testEveryConvert()
        {
            Console.WriteLine("测试用数字:n3.15,3.45,3.5,3.55,3.65,3.75,3.85,3.95,4.0,-3.15, -3.45, -3.5,  -3.55 -3.95, -4.0");
            double[] testNum = { 3.15,3.45,3.5,3.55, 3.65, 3.75, 3.85, 3.95, 4.0 ,-3.15, -3.45, -3.5, -3.55, -3.95, -4.0};
            Console.WriteLine("Math.Floor()舍去小数取整,取小于等于当前数据的最小整数");
            foreach (var f in testNum)
            {
                Console.Write(Math.Floor(f) + "   ");
            }
            Console.WriteLine();
            Console.WriteLine("Math.Round()四舍五入取整,中间取偶数");
            foreach (var r in testNum)
            { // www.jb200.com
                Console.Write(Math.Round(r) + "   ");
            }
            Console.WriteLine();
            Console.WriteLine("Math.Ceiling()凑整,取大于等于当前数据的最小整数");
            foreach (var c in testNum)
            {
                Console.Write(Math.Ceiling(c) + "   ");
            }
           
            Console.WriteLine();
            Console.WriteLine("Truncate()截取,舍去小数部分");
            foreach (var t in testNum)
            {
                Console.Write(Math.Truncate(t) + "   ");
            }
            Console.WriteLine();
            Console.ReadLine();
        }