Post

# How To Get First N Digits Of A Number

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.
1. /// <summary>
2. /// Returns first part of number.
3. /// </summary>
4. /// <param name="number">Initial number</param>
5. /// <param name="N">Amount of digits required</param>
6. /// <returns>First part of number</returns>
7. private static int takeNDigits(int number, int N)
8. {
9. // this is for handling negative numbers, we are only insterested in postitve number
10. number =Math.Abs(number);
11. // special case for 0 as Log of 0 would be infinity
12. if(number == 0)
13. return number;
14. // getting number of digits on this input number
15. int numberOfDigits = (int)Math.Floor(Math.Log10(number) + 1);
16. // check if input number has more digits than the required get first N digits
17. if (numberOfDigits >= N)
18. return (int)Math.Truncate((number / Math.Pow(10, numberOfDigits - N)));
19. else
20. return number;
21. }
I tested with some inputs, which are given below.
1. int Result1 = takeNDigits(666, 4);
2. int Result2 = takeNDigits(987654321, 5);
3. int Result3 = takeNDigits(123456789, 7);
4. int Result4 = takeNDigits(35445, 1);
5. int Result5 = takeNDigits(666555, 6);
The output is shown below.
1. Result1: 666
2. Result2: 98765
3. Result3: 1234567
4. Result4: 3
5. Result5: 666555
Next Recommended Reading C# 7 Digit Separator