Udemy

How to get First N digits of a number without Converting to String

Thursday, November 05, 2015 0 Comments A+ a-

Few days back i was asked by my senior colleague to make a method which takes two arguments as input, first the number and second the number of digits to be returned from the first argument number.

After sometime i was able to make logic of it, which was to get the number of digits of the input number and then i used that to get the number of digits using second parameter.


Here is the method:

        private static int takeNDigits(int number, int N)
        {
            int numberOfDigits = (int)Math.Floor(Math.Log10(number) + 1);

            if (numberOfDigits >= N)
                return (int)Math.Truncate((number / Math.Pow(10, numberOfDigits - N)));
            else
                return number;

        }


 and use it :

            int Result1 = takeNDigits(666, 4);
            int Result2 = takeNDigits(987654321, 5);
            int Result3 = takeNDigits(123456789, 7);
            int Result4 = takeNDigits(35445, 1);
            int Result5 = takeNDigits(666555, 6);

Output:


Result1 : 666
Result2 : 98765
Result3 : 1234567
Result4 : 3
Result5 : 666555