Jul
8
2010

# How to Get the Last Number of an Integer

When I teach my introduction to C# course, I typically provide a tough numeric challenge to stimulate thinking and use all the features of the language learned up to that point.  In a recent class, I was presented the challenge of determining the last number of any integer.  For example:

• 12 == 2
• 337 == 7
• 1000 == 0
• 987654 == 4

In each example above, I needed to simply return whatever was in the “singles” place – the last number of the number.

My first approach felt like I was cheating, but it worked:

```public static int GetLastNumber(string stringifiedNumber)
{
return Convert.ToInt32(stringifiedNumber[stringifiedNumber.Length -1].ToString());
}// method```

After brooding over it, I decided to challenge myself to do this mathematically instead.  Here is the final code:

```public static int GetLastNumber(dynamic anyNumber)
{
double fractional = anyNumber * .1;
double truncated = Math.Truncate(fractional);
return (int)(Math.Round((fractional - truncated),1) * 10);
}// method```

The use of the dynamic keyword above allows me to pass in any numeric data type.

Updated: Thanks to Nicki for identifying how I over-engineered this problem.  I simply needed to get the modulus of 10 to get what I wanted.  So in one simple statement I could write:

` anyNumber % 10;`
Copyright © Microsoft Corporation. All rights reserved.
The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
blog comments powered by Disqus