Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to get the Nth digit of a number in C#

1 Answer

0 votes
using System;

namespace DigitExample
{
    internal static class Program
    {
         /// <summary>
        /// Returns the N-th digit of a number counting from the left.
        /// </summary>
        private static int GetDigitFromLeft(long number, int position)
        {
            string digits = Math.Abs(number).ToString();
        
            if (position < 1 || position > digits.Length) {
                throw new ArgumentOutOfRangeException(
                    nameof(position),
                    "Position is out of range.");
            }
        
            return digits[position - 1] - '0';
        }

        private static void Main()
        {
            long number = 72948;

            Console.WriteLine($"Number: {number}");
            Console.WriteLine($"1st digit from right: {GetDigitFromLeft(number, 1)}");
            Console.WriteLine($"3rd digit from right: {GetDigitFromLeft(number, 3)}");
            Console.WriteLine($"5th digit from right: {GetDigitFromLeft(number, 5)}");
        }
    }
}


/*
run:

Number: 72948
1st digit from right: 7
3rd digit from right: 9
5th digit from right: 8

*/

 



answered 2 days ago by avibootz
...