【问题标题】:What is the most efficient way to truncate a number for a specific accuracy?为特定精度截断数字的最有效方法是什么?
【发布时间】:2011-02-21 18:31:22
【问题描述】:

为了特定精度截断数字的最有效方法是什么?

【问题讨论】:

  • 从其他答案看来,这里似乎发生了一些 ESP。我不是通灵者,请您详细说明一下。
  • @leppie:来自修订版 1:I want to get the only 3 digits of the milliseconds of System.DateTime.

标签: c# math int


【解决方案1】:
int ms = Convert.ToInt32(
             Convert.ToString(DateTime.Now.Millisecond).Substring(0, 3));

double Length = Math.Pow(10, (DateTime.Now.Millisecond.ToString().Length - 3));

double Truncate = Math.Truncate((double)DateTime.Now.Millisecond / Length);

编辑:

在我将发布的代码上运行以下两个代码后,由于变量的重用,double 方法运行良好。在 5,000,000 次 DateTime.Now 的迭代中(其中许多将被两次检查跳过),SubString() 方法耗时 9598 毫秒,Double 方法耗时 6754 毫秒。

EDIT#2:在 * 1000 中编辑到测试中以确保迭代正在运行。

用于测试的代码如下:

        Stopwatch stop = new Stopwatch();
        stop.Start();

        for (int i = 0; i < 5000000; i++)
        {
            int MSNow = DateTime.Now.Millisecond * 1000;

            if (MSNow.ToString().Length > 2)
            {
                int ms = Convert.ToInt32(
                    Convert.ToString(MSNow).Substring(0, 3));
            }
        }

        stop.Stop();

        Console.WriteLine(stop.ElapsedMilliseconds);

        stop = new Stopwatch();
        stop.Start();

        for (int i = 0; i < 5000000; i++)
        {
            int MSNow = DateTime.Now.Millisecond * 1000;
            int lengthMS = MSNow.ToString().Length;

            if (lengthMS > 2)
            {
                double Length = Math.Pow(10, (lengthMS - 3));
                double Truncate = Math.Truncate((double)MSNow / Length);
            }
        }

        stop.Stop();

        Console.Write(stop.ElapsedMilliseconds);

        Console.ReadKey();

【讨论】:

  • 什么是最高效的方式?
  • @stacker - 两个都取,然后通过Stopwatch 运行它们,看看哪个更快?
  • 我会说Math.Pow 慢得多,但这只是一个猜测,用StopWatch 测试一下。
  • @IVlad,我也这么猜,double 计算。我现在做计算看看。
  • @Stacker - 有一些数据给你。
【解决方案2】:

DateTime 中,Milliseconds 始终包含在 0 到 999 之间,因此您无需执行任何操作。

【讨论】:

  • 引用我在回答“毫秒组件,表示为 0 到 999 之间的值”中发布的 MSDN 链接。似乎合乎逻辑,一个月内不能有 32 天,一秒内不能超过 999 毫秒。
【解决方案3】:
Math.Floor(num * Math.Pow(10, x) + 0.5) / Math.Pow(10, x)

你的精确度在哪里

【讨论】:

  • 好吧,我想我已经给出了断章取义的答案。但是我以为您要进行舍入,无论如何我无法理解截断甚至在数字上的含义,无论如何抱歉没有了解上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
相关资源
最近更新 更多