Click here to Skip to main content
15,116,214 members
Articles / Programming Languages / C#
Tip/Trick
Posted 28 Apr 2016

Tagged as

Stats

43.5K views
13 bookmarked

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

Share

About the Author

Ehsan Sajjad
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 3:57
MemberPawel Sienko6-May-16 3:57 
AnswerRe: Performance question Pin
Ehsan Sajjad6-May-16 4:22
professionalEhsan Sajjad6-May-16 4:22 
QuestionMy Vote of 4 Pin
hooodaticus5-May-16 6:27
Memberhooodaticus5-May-16 6:27 
QuestionMy try Pin
asimonassi4-May-16 20:49
Memberasimonassi4-May-16 20:49 
AnswerRe: My try Pin
Ehsan Sajjad5-May-16 1:01
professionalEhsan Sajjad5-May-16 1:01 
GeneralRe: My try Pin
asimonassi5-May-16 1:09
Memberasimonassi5-May-16 1:09 
GeneralRe: My try Pin
Ehsan Sajjad5-May-16 1:11
professionalEhsan Sajjad5-May-16 1:11 
GeneralRe: My try Pin
hooodaticus5-May-16 6:36
Memberhooodaticus5-May-16 6:36 
GeneralRe: My try Pin
asimonassi3-Jun-16 8:04
Memberasimonassi3-Jun-16 8:04 
QuestionHere's a potential real world reason... Pin
Jim Meadors4-May-16 20:10
MemberJim Meadors4-May-16 20:10 
QuestionWhy? Pin
bling3-May-16 18:09
Memberbling3-May-16 18:09 
AnswerRe: Why? Pin
Ehsan Sajjad4-May-16 0:06
professionalEhsan Sajjad4-May-16 0:06 
QuestionGenuine real world application Pin
CHill603-May-16 6:27
mveCHill603-May-16 6:27 
AnswerRe: Genuine real world application Pin
Ehsan Sajjad11-Jan-18 8:11
professionalEhsan Sajjad11-Jan-18 8:11 
SuggestionCheck 0 value Pin
TizVic1-May-16 23:34
MemberTizVic1-May-16 23:34 
SuggestionNames of variables, N? Add intellisense so coders can quickly understand? Pin
AORD29-Apr-16 12:29
MemberAORD29-Apr-16 12:29 
GeneralRe: Names of variables, N? Add intellisense so coders can quickly understand? Pin
Ehsan Sajjad2-May-16 0:03
professionalEhsan Sajjad2-May-16 0:03 
Question+5 Pin
Raje_28-Apr-16 21:51
MemberRaje_28-Apr-16 21:51 
Thumbs Up | :thumbsup:
AnswerRe: +5 Pin
Ehsan Sajjad24-Feb-17 23:34
professionalEhsan Sajjad24-Feb-17 23:34 
QuestionDavid Pin
DavidSWashington28-Apr-16 20:30
MemberDavidSWashington28-Apr-16 20:30 
AnswerRe: David Pin
Ehsan Sajjad24-Feb-17 23:35
professionalEhsan Sajjad24-Feb-17 23:35 
QuestionHave you tested it with negative numbers? PinPopular
George Swan28-Apr-16 14:04
MemberGeorge Swan28-Apr-16 14:04 
AnswerRe: Have you tested it with negative numbers? Pin
Ehsan Sajjad2-May-16 0:28
professionalEhsan Sajjad2-May-16 0:28 
GeneralMy vote of 5 Pin
Dmitriy Gakh28-Apr-16 8:43
professionalDmitriy Gakh28-Apr-16 8:43 
Question3, But Why?? PinPopular
Kevin Marois28-Apr-16 6:41
professionalKevin Marois28-Apr-16 6: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.