How to Return the Last Digit of a Number in Bash

How to Return the Last Digit of a Number in Bash

A Step-by-Step Guide

Introduction

In one of my articles, I wrote extensively on what the shell, the terminal and what they are, how they relate to each other, so you can check it here, if you are new to Bash or else, you can move straight to the main thing.

How to Return the Last Digit of a Number in Bash

To return the last digit of a number in bash, we are going to be taking advantage of the modular operator %, with this operator, irrespective of the length of a number, so far it is a decimal number (number in base 10), whenever we use the modular operator with 10, it will divide the number by 10 and return only the remainder of that number, which will always be the last digit of that number irrespective of the length of the number.

Examples of Returning the Last Digit of a Number in Bash

Let us take these sets of numbers, for instance, 57, 412, 8546, 55298, 421574 and 3645849, to get the last digit of these numbers, we just need to divide each of the numbers by the modulus of 10, %10 which will then return the last digit for us. Here are examples of that:

Conclusion

You can also apply this general concept to other programming languages like C, C++, JavaScript, Java etc. to find the last digit of any number.

Thank you for reading, please let's connect on Twitter and LinkedIn.