15,179,246 members
Articles / Programming Languages / C#
Tip/Trick
Posted 28 Apr 2016

45.1K views
13 bookmarked

# Get First N Digits of a Number

Rate me:
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)

## About the Author

 Software Developer 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

 First PrevNext
 Performance question Pawel Sienko6-May-16 3:57 Pawel Sienko 6-May-16 3:57
 Re: Performance question Ehsan Sajjad6-May-16 4:22 Ehsan Sajjad 6-May-16 4:22
 My Vote of 4 hooodaticus5-May-16 6:27 hooodaticus 5-May-16 6:27
 My try asimonassi4-May-16 20:49 asimonassi 4-May-16 20:49
 Re: My try Ehsan Sajjad5-May-16 1:01 Ehsan Sajjad 5-May-16 1:01
 Re: My try asimonassi5-May-16 1:09 asimonassi 5-May-16 1:09
 Re: My try Ehsan Sajjad5-May-16 1:11 Ehsan Sajjad 5-May-16 1:11
 Re: My try hooodaticus5-May-16 6:36 hooodaticus 5-May-16 6:36
 Re: My try asimonassi3-Jun-16 8:04 asimonassi 3-Jun-16 8:04
 Here's a potential real world reason... Jim Meadors4-May-16 20:10 Jim Meadors 4-May-16 20:10
 I'm working on a SVG Font Editor and about to embark on functions to rescale the individual glyphs. I have already converted the string text (from the XML) to paths in GDI. In order to drag a point and have the drawing keep up with reality, It may be beneficial to run such a function. The reason being that whole numbers represent pixels and the recalculated points each time could be expected to process faster by shaving decimal places during this phase. And none of the truncated points would make any significant difference to the final drawing. Jim Meadors
 Why? bling3-May-16 18:09 bling 3-May-16 18:09
 Re: Why? Ehsan Sajjad4-May-16 0:06 Ehsan Sajjad 4-May-16 0:06
 Genuine real world application CHill603-May-16 6:27 CHill60 3-May-16 6:27
 Re: Genuine real world application Ehsan Sajjad11-Jan-18 8:11 Ehsan Sajjad 11-Jan-18 8:11
 Check 0 value TizVic1-May-16 23:34 TizVic 1-May-16 23:34
 Names of variables, N? Add intellisense so coders can quickly understand? AORD29-Apr-16 12:29 AORD 29-Apr-16 12:29
 Re: Names of variables, N? Add intellisense so coders can quickly understand? Ehsan Sajjad2-May-16 0:03 Ehsan Sajjad 2-May-16 0:03
 +5 Raje_28-Apr-16 21:51 Raje_ 28-Apr-16 21:51
 Re: +5 Ehsan Sajjad24-Feb-17 23:34 Ehsan Sajjad 24-Feb-17 23:34
 David DavidSWashington28-Apr-16 20:30 DavidSWashington 28-Apr-16 20:30
 Re: David Ehsan Sajjad24-Feb-17 23:35 Ehsan Sajjad 24-Feb-17 23:35
 Have you tested it with negative numbers? George Swan28-Apr-16 14:04 George Swan 28-Apr-16 14:04
 Re: Have you tested it with negative numbers? Ehsan Sajjad2-May-16 0:28 Ehsan Sajjad 2-May-16 0:28
 My vote of 5 Dmitriy Gakh28-Apr-16 8:43 Dmitriy Gakh 28-Apr-16 8:43
 3, But Why?? Kevin Marois28-Apr-16 6:41 Kevin Marois 28-Apr-16 6:41
 Last Visit: 31-Dec-99 19:00     Last Update: 27-Jan-22 8:44 Refresh 12 Next ᐅ

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

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