Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to truncate a number for a specific accuracy?

Tags:

c#

int

math

What is the most efficient way to truncate a number for a specific accuracy?

like image 647
stacker Avatar asked Oct 14 '22 05:10

stacker


2 Answers

In a DateTime, Milliseconds are always comprised between 0 and 999 so you don't have anything to do.

like image 150
Julien Lebosquain Avatar answered Oct 28 '22 22:10

Julien Lebosquain


int ms = Convert.ToInt32(
             Convert.ToString(DateTime.Now.Millisecond).Substring(0, 3));

or

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

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

EDIT:

After running both the below on the code I will post, the double method works well due to reuse of variables. Over an iteration of 5,000,000 DateTime.Now's (in which many will be skipped by both checks), the SubString() method took 9598ms, and the Double method took 6754ms.

EDIT#2: Edited in * 1000 into tests to make sure the iterations are running.

Code used to test as follows:

        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();
like image 23
Kyle Rosendo Avatar answered Oct 28 '22 21:10

Kyle Rosendo