【发布时间】:2011-02-21 18:31:22
【问题描述】:
为了特定精度截断数字的最有效方法是什么?
【问题讨论】:
-
从其他答案看来,这里似乎发生了一些 ESP。我不是通灵者,请您详细说明一下。
-
@leppie:来自修订版 1:
I want to get the only 3 digits of the milliseconds of System.DateTime.
为了特定精度截断数字的最有效方法是什么?
【问题讨论】:
I want to get the only 3 digits of the milliseconds of System.DateTime.
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();
【讨论】:
Stopwatch 运行它们,看看哪个更快?
Math.Pow 慢得多,但这只是一个猜测,用StopWatch 测试一下。
double 计算。我现在做计算看看。
在DateTime 中,Milliseconds 始终包含在 0 到 999 之间,因此您无需执行任何操作。
【讨论】:
Math.Floor(num * Math.Pow(10, x) + 0.5) / Math.Pow(10, x)
你的精确度在哪里
【讨论】: