ArticleZip > How To Get Last Digit Of Number

How To Get Last Digit Of Number

When working with numbers in software development, it's common to encounter situations where you need to extract specific digits for various operations. One of the frequently asked questions is how to get the last digit of a number. In this article, we will explore simple and efficient methods to achieve this in different programming languages, helping you enhance your coding skills.

Let's dive into the solutions for extracting the last digit of a number in various programming languages.

1. Using Modulo Operator in Python:
Python provides a straightforward way to get the last digit of a number using the modulo operator (%) which returns the remainder of a division operation. By dividing the input number by 10 and taking the remainder, we can obtain the last digit.

Python

number = 123456
last_digit = number % 10
print("The last digit of", number, "is", last_digit)

2. Using Modulus Operator in JavaScript:
In JavaScript, the modulus operator (%) works similarly to Python. We can apply the same approach to extract the last digit of a number.

Javascript

const number = 789012;
const lastDigit = number % 10;
console.log(`The last digit of ${number} is ${lastDigit}`);

3. Using Integer Division in C++:
In C++, you can use integer division to truncate the number and get the last digit by considering only the remainder.

Cpp

#include 
using namespace std;

int main() {
    int number = 456789;
    int lastDigit = number % 10;
    cout << "The last digit of " << number << " is " << lastDigit << endl;
    return 0;
}

4. Using Math Functions in Java:
Java provides built-in math functions that make it easy to extract the last digit of a number.

Java

public class LastDigit {
    public static void main(String[] args) {
        int number = 987654;
        int lastDigit = Math.abs(number % 10);
        System.out.println("The last digit of " + number + " is " + lastDigit);
    }
}

By following these simple techniques in Python, JavaScript, C++, and Java, you can efficiently retrieve the last digit of a number in your programming tasks. Remember, understanding the basics of arithmetic operations in different languages can significantly improve your coding capabilities and problem-solving skills.

Next time you come across a scenario where you need to work with the last digit of a number, you can confidently apply these methods to streamline your code and enhance your programming experience. Happy coding!

×