阅读背景:

C#中保留两位小数但不四舍五入的最优做法

来源:互联网 

多种做法比较

    class Program_保留两位小数但不四舍五入
    {
        static void Main(string[] args)
        {
            Helper.Run(delegate ()
            {
                method1();
            }, 1000000, " 1.先乘后除,再强制类型转换 ");

            Helper.Run(delegate ()
            {
                method2();
            }, 1000000, " 2.使用substring截取字符串,然后转换 ");

            Helper.Run(delegate ()
            {
                method4();
            }, 1000000, " 4.使用math.floor ");

            Helper.Run(delegate ()
            {
                method5();
            }, 1000000, " 5.使用正则来处理字符串数据,然后再类型转换 ");

            Console.ReadKey();
        }

        const double num = 15.1257;

        static void method1()
        {
            var tmp = (int)(num * 100) / 100.00;
        }

        static void method2()
        {
            var str = (num).ToString();
            var tmp = double.Parse(str.Substring(0, str.IndexOf('.') + 3));
        }

        //static void method3()
        //{
        //    var tmp = double.Parse((num).ToString("#0.00"));
        //}

        static void method4()
        {
            var tmp = Math.Floor(num * 100) / 100.00;
        }

        static void method5()
        {
            var tmp = double.Parse(Regex.Match(num.ToString(), @"[\d]+.[\d]{0,2}").Value);
        }

        //结果:method1 最快,而使用系统的方法或者字符串截取的方法都会慢一些
    }
    class Program_保留两位小数但不四舍五入
   



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: