Introduction
This code snippet returns the first N digits of a number without converting the number to the string.
Background
I was asked by my senior colleague to make a method, which takes two arguments as an input. First is the number and second is the number of digits to be returned from the first argument number, but the restriction was not to convert it to the string.
Code
I came up with this method, which worked pretty well for me.
- /// <summary>
- /// Returns first part of number.
- /// </summary>
- /// <param name="number">Initial number</param>
- /// <param name="N">Amount of digits required</param>
- /// <returns>First part of number</returns>
- private static int takeNDigits(int number, int N)
- {
- // this is for handling negative numbers, we are only insterested in postitve number
- number =Math.Abs(number);
- // special case for 0 as Log of 0 would be infinity
- if(number == 0)
- return number;
- // getting number of digits on this input number
- int numberOfDigits = (int)Math.Floor(Math.Log10(number) + 1);
- // check if input number has more digits than the required get first N digits
- if (numberOfDigits >= N)
- return (int)Math.Truncate((number / Math.Pow(10, numberOfDigits - N)));
- else
- return number;
- }
- 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);
- Result1: 666
- Result2: 98765
- Result3: 1234567
- Result4: 3
- Result5: 666555

SubashPosted Mar 15, 2017, 12:15 AM
Easy one but mathematical expressions confusing me LOL!!