Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

Get First N Digits of a Number

Rate me:
Please Sign up or sign in to vote.
4.34/5 (28 votes)
3 May 2016CPOL 61.8K   13   50
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Ehsan Sajjad is a Microsoft Certified Professional, Microsoft Certified C# Specialist and he is also among the top users on StackOverflow from Pakistan with 50k+ reputation at time of writing this and counting.

He is a passionate software developer with around 5 years of professional experience in Microsoft Technologies both web and desktop applications and always open to learn new things and platforms especially in mobile application development and game development.

Some Achievements :

  • 5th Top Contributor from Pakistan on Stackoverflow.com
  • Top User in ASP.NET MVC from Pakistan on Stackoverflow.com
  • 21st June 2017 - Article of the Day - ASP.NET Community (Beginners Guide on AJAX CRUD Operations in Grid using JQuery DataTables in ASP.NET MVC 5)
  • 19th April 2017 - Article of the Day - ASP.NET Community (ASP.NET MVC Async File Uploading using JQuery)
  • March 2017 - Visual C# Technical Guru Silver Medal on Microsoft Tech Net Wiki Article Competition
  • 20 January 2017 - Article of the Day - ASP.NET Community (Async File Uploading in ASP.NET MVC)
  • 22nd September 2016 - Article of the Day - ASP.NET Community (GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5)
  • 22nd August 2016 - Article of the Day - ASP.NET Community (Beginners Guide for Creating GridView in ASP.NET MVC 5)
  • December 2015 - C-SharpCorner Monthly Winner

Comments and Discussions

 
QuestionPerformance question Pin
Pawel Sienko6-May-16 2:57
Pawel Sienko6-May-16 2:57 
AnswerRe: Performance question Pin
Ehsan Sajjad6-May-16 3:22
professionalEhsan Sajjad6-May-16 3:22 
QuestionMy Vote of 4 Pin
hooodaticus5-May-16 5:27
hooodaticus5-May-16 5:27 
QuestionMy try Pin
Andrea Simonassi4-May-16 19:49
Andrea Simonassi4-May-16 19:49 
AnswerRe: My try Pin
Ehsan Sajjad5-May-16 0:01
professionalEhsan Sajjad5-May-16 0:01 
GeneralRe: My try Pin
Andrea Simonassi5-May-16 0:09
Andrea Simonassi5-May-16 0:09 
GeneralRe: My try Pin
Ehsan Sajjad5-May-16 0:11
professionalEhsan Sajjad5-May-16 0:11 
GeneralRe: My try Pin
hooodaticus5-May-16 5:36
hooodaticus5-May-16 5:36 
GeneralRe: My try Pin
Andrea Simonassi3-Jun-16 7:04
Andrea Simonassi3-Jun-16 7:04 
QuestionHere's a potential real world reason... Pin
Jim Meadors4-May-16 19:10
Jim Meadors4-May-16 19:10 
QuestionWhy? Pin
bling3-May-16 17:09
bling3-May-16 17:09 
AnswerRe: Why? Pin
Ehsan Sajjad3-May-16 23:06
professionalEhsan Sajjad3-May-16 23:06 
QuestionGenuine real world application Pin
CHill603-May-16 5:27
mveCHill603-May-16 5:27 
AnswerRe: Genuine real world application Pin
Ehsan Sajjad11-Jan-18 7:11
professionalEhsan Sajjad11-Jan-18 7:11 
SuggestionCheck 0 value Pin
TizVic1-May-16 22:34
TizVic1-May-16 22:34 
SuggestionNames of variables, N? Add intellisense so coders can quickly understand? Pin
AORD29-Apr-16 11:29
AORD29-Apr-16 11:29 
GeneralRe: Names of variables, N? Add intellisense so coders can quickly understand? Pin
Ehsan Sajjad1-May-16 23:03
professionalEhsan Sajjad1-May-16 23:03 
Added. Thanks for pointing that out. Smile | :)
Question+5 Pin
Raje_28-Apr-16 20:51
Raje_28-Apr-16 20:51 
AnswerRe: +5 Pin
Ehsan Sajjad24-Feb-17 22:34
professionalEhsan Sajjad24-Feb-17 22:34 
QuestionDavid Pin
DavidSWashington28-Apr-16 19:30
DavidSWashington28-Apr-16 19:30 
AnswerRe: David Pin
Ehsan Sajjad24-Feb-17 22:35
professionalEhsan Sajjad24-Feb-17 22:35 
QuestionHave you tested it with negative numbers? PinPopular
George Swan28-Apr-16 13:04
mveGeorge Swan28-Apr-16 13:04 
AnswerRe: Have you tested it with negative numbers? Pin
Ehsan Sajjad1-May-16 23:28
professionalEhsan Sajjad1-May-16 23:28 
GeneralMy vote of 5 Pin
Dmitriy Gakh28-Apr-16 7:43
professionalDmitriy Gakh28-Apr-16 7:43 
Question3, But Why?? PinPopular
Kevin Marois28-Apr-16 5:41
professionalKevin Marois28-Apr-16 5:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.