• c# 重新认识 Double 浮点型


    double test1 = 0;
    for (int i = 0; i < 100000000; i++)
    {
    test1 += 0.0001;
    }

    请问 test1 的值是几?

    答案是:9999.99999919852(本次测试结果)

    拿 Decimal 重新测试一次,结果是正确的

    下面是测试代码

     1  static void Main(string[] args)
     2         {
     3             Stopwatch sp = new Stopwatch();
     4             sp.Start();
     5 
     6             double test1 = 0;
     7             for (int i = 0; i < 100000000; i++)
     8             {
     9                 test1 += 0.0001;
    10             }
    11             sp.Stop();
    12             string str1 = string.Format("double 类型 0.0001 累加10万次 值[{0}] 耗时[{1}]", test1.ToString(), sp.ElapsedMilliseconds.ToString()); 
    13             Console.WriteLine(str1); 
    14 
    15             sp.Restart(); 
    16             decimal test2 = 0;
    17             for (int i = 0; i < 100000000; i++)
    18             {
    19                 test2 += Convert.ToDecimal(0.0001);
    20             }
    21             sp.Stop();
    22             string str2 = string.Format("decimal类型 0.0001 累加10万次 值[{0}] 耗时[{1}]", test2.ToString(), sp.ElapsedMilliseconds.ToString()); 
    23             Console.WriteLine(str2);
    24 
    25             sp.Restart(); 
    26             double test5 = 0;
    27             for (int i = 0; i < 100000000; i++)
    28             {
    29                 test5 += 0.5;
    30             }
    31             sp.Stop(); 
    32             string str3 = string.Format("double 类型 0.5    累加10万次 值[{0}] 耗时[{1}]", test5.ToString(), sp.ElapsedMilliseconds.ToString());
    33             Console.WriteLine(str3);
    34 
    35             sp.Restart(); 
    36             double test25 = 0;
    37             for (int i = 0; i < 100000000; i++)
    38             {
    39                 test25 += 0.25;
    40             }
    41             sp.Stop(); 
    42             string str4 = string.Format("double 类型 0.25   累加10万次 值[{0}] 耗时[{1}]", test5.ToString(), sp.ElapsedMilliseconds.ToString());
    43             Console.WriteLine(str4);
    44 
    45             sp.Restart();
    46             double test6 = 0;
    47             for (int i = 0; i < 100000000; i++)
    48             {
    49                 test6 += 0.6;
    50             }
    51             sp.Stop();
    52             string str5 = string.Format("double 类型 0.6    累加10万次 值[{0}] 耗时[{1}]", test6.ToString(), sp.ElapsedMilliseconds.ToString());
    53             Console.WriteLine(str5);
    54 
    55 
    56             Console.ReadKey();
    57         }

    Decimal 不丢失精度,但是慢 

    double   丢失精度 ,速度快,对数据要求不严格推荐使用。     1/2 时,不丢失精度

    网上查到的相关文章  

    float,double等精度丢失问题

  • 相关阅读:
    Mysql任务调度
    使用 IntraWeb (18)
    使用 IntraWeb (17)
    替盛大代发的招聘启示
    使用 IntraWeb (16)
    使用 IntraWeb (15)
    使用 IntraWeb (14)
    使用 IntraWeb (13)
    使用 IntraWeb (12)
    使用 IntraWeb (11)
  • 原文地址:https://www.cnblogs.com/asktao/p/6119218.html
Copyright © 2020-2023  润新知