Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get First N Digits of a Number

0.00/5 (No votes)
3 May 2016 3  
This is about how to get the first N digits of a number without converting it to string

Introduction

This snippet returns the first N digits of a number without converting the number to string.

Background

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, but the restriction was not to convert it to string.

Using the 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;
}  

I tested with some inputs which are:

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);  

The output was:

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

Points of Interest

The thing that took me some time was to figure out how to determine the number of digits the input number has, but after some effort and research, I was able to get to it.

History

  • 04/28/2016: Initial version
  • 04/30/2016: Documentation addition as suggested in comments
  • 05/03/2016 Handled case of 0 and negative numbers

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here