In the blogpost, we’ll learn several ways of extracting first and last digits of a number in JavaScript. We’ll explore several Math, String, recursion functions. Then learn some common mistakes and lastly, cement our understanding with a fun practice question.
Lets dive in! 👨💻
- Ways to extract first and last digits in JavaScript
- Using Modulo Operator to get Last Digit in JavaScript
- Using String Conversion and Bracket Notation to get first & last digits in JavaScript
- Using the slice() Method to get first & last digits in JavaScript
- Using Loops to get first digit in JavaScript
- Recursive Function to find first digit in JavaScript
- Using Math Functions (log and power) to get first digit in JavaScript
- Using Regular Expressions to find first digit in JavaScript
- Using String.match() and Array.pop() to find last digit in JavaScript
- Tips & errors while extracting first and last digits in JavaScript
- 🧪Practice Coding Problem
Ways to extract first and last digits in JavaScript
Using Modulo Operator to get Last Digit in JavaScript
The modulo operator (%
) is used to find the remainder of a division between two numbers. Any decimal number (base 10) when divided by 10 leaves its last digit as the remainder.
For negative numbers, try to use Math.abs()
so that negative remainder isn’t obtained.
- In following code example,
12345 % 10
gives5
, which is the last digit of the number12345
. Same for negative.
// Positive Number
let positiveNumber = 12345;
let positiveLastDigit = positiveNumber % 10;
console.log(positiveLastDigit); // Output: 5
// Negative Number
let negativeNumber = -12345;
let negativeLastDigit = Math.abs(negativeNumber) % 10;
console.log(negativeLastDigit); // Output: 5
Using String Conversion and Bracket Notation to get first & last digits in JavaScript
This method involves converting a number to its string representation. Once a number is converted to a string, you can access its characters (digits) using bracket notation, similar to accessing array elements. The first character (digit) is at index 0
, and the last character (digit) can be accessed using string.length - 1
.
For negative number, first character can be minus sign, so either take Math.abs()
and process like positive number, or else look at second character (1st index, not 0th).
In following example, posNumber.toString()
converts the number to a string, and then the first and last digits are accessed using bracket notation. For negative number, we take the 2nd character (1st index) as first digit.
// Positive Number
let posNumber = 12345;
let posNumberStr = posNumber.toString();
let posFirstDigit = posNumberStr[0];
let posLastDigit = posNumberStr[posNumberStr.length - 1];
console.log(
`First digit: ${posFirstDigit}, Last digit: ${posLastDigit}`,
);
// Output: First digit: 1, Last digit: 5
// Negative Number
let negNumber = -12345;
let negNumberStr = negNumber.toString();
let negFirstDigit = negNumberStr[1]; // 0 is the '-' sign
let negLastDigit = negNumberStr[negNumberStr.length - 1];
console.log(
`First digit: ${negFirstDigit}, Last digit: ${negLastDigit}`,
);
// Output: First digit: 1, Last digit: 5
Using the slice() Method to get first & last digits in JavaScript
The slice()
method is a string method in JavaScript that returns a section of a string without modifying the original string. When you convert a number to a string, you can use slice()
to extract the first and last digits. To get the first digit, you slice from index 0
to 1
. To get the last digit, you slice from index -1
, which represents the last character in a string.
For negative numbers, first digit can be extracted between 1
to 2
index.
In following example, posNumberStr.slice(0, 1)
returns the substring from index 0
to 1
(not including 1
), which is the first digit. posNumberStr.slice(-1)
returns the last character of the string, which is the last digit. But for first digit of negative number, we use negNumberStr.slice(1, 2)
to skip the negative sign as first character.
// Positive Number
let posNumber = 12345;
let posNumberStr = posNumber.toString();
let posFirstDigit = posNumberStr.slice(0, 1);
let posLastDigit = posNumberStr.slice(-1);
console.log(
`First digit: ${posFirstDigit}, Last digit: ${posLastDigit}`,
);
// Output: First digit: 1, Last digit: 5
// Negative Number
let negNumber = -12345;
let negNumberStr = negNumber.toString();
let negFirstDigit = negNumberStr.slice(1, 2); // Adjust slice to skip '-'
let negLastDigit = negNumberStr.slice(-1);
console.log(
`First digit: ${negFirstDigit}, Last digit: ${negLastDigit}`,
);
// Output: First digit: 1, Last digit: 5
Using Loops to get first digit in JavaScript
This method involves using a loop to repeatedly divide the number by 10 until it becomes a single-digit number. Each division by 10 effectively removes the last digit of the number. The loop continues until the number is less than 10, at which point the number itself is the first digit.
To accommodate negative numbers, just use absolute value of the number.
In following example, we first take absolute value of number (as loop will be skipped for negative numbers, and flooring and division will also cause incorrect calculations). Then a while
loop keeps dividing number
by 10 and floors the result (to handle cases where number
is not a whole number). When number
becomes less than 10, the loop exits, and number
is the first digit.
function getFirstDigitLoop(number) {
number = Math.abs(number);
while (number >= 10) {
number = Math.floor(number / 10);
}
return number;
}
let firstDigitPos = getFirstDigitLoop(12345);
let firstDigitNeg = getFirstDigitLoop(-12345);
console.log(`Positive number first digit: ${firstDigitPos}`);
// Output: "Positive number first digit: 1"
console.log(`Negative number first digit: ${firstDigitNeg}`);
// Output: "Negative number first digit: 1"
Recursive Function to find first digit in JavaScript
Using recursion, a function calls itself with a modified parameter until it reaches a base condition. In this context, the recursive function reduces the number by dividing it by 10 in each call until it becomes a single-digit number, which is then returned as the first digit.
For negative numbers, the recursive function could operate on the absolute value of the number (Math.abs()
).
In following recursive function, getFirstDigit
, if number
is less than 10 (the base case), it returns number
. Otherwise, it calls itself with number
divided by 10. The recursion continues until it reaches a single-digit number, which is then returned as the first digit.
function getFirstDigit(number) {
number = Math.abs(number);
if (number < 10) {
return number;
} else {
return getFirstDigit(Math.floor(number / 10));
}
}
let firstDigit = getFirstDigit(-12345);
console.log(firstDigit); // Output: 1
Using Math Functions (log and power) to get first digit in JavaScript
Math functions in JavaScript can be creatively used to isolate the first digit of a number. The idea is to use Math.log10()
to determine how many times the number can be divided by 10 before it becomes a single-digit number. Then, using Math.floor()
along with this information, you can isolate the first digit.
For negative numbers, again we can use Math.abs()
.
In following example, Math.log10(number)
calculates the logarithm of the number to the base 10, which is about the number of digits minus one. Math.floor()
then rounds it down to the nearest whole number, and Math.pow(10, digits)
gives 10 raised to this number. Finally, dividing the original number by this value and flooring it gives the first digit.
let number = Math.abs(-12345);
let firstDigit = Math.floor(
number / Math.pow(10, Math.floor(Math.log10(number))),
);
console.log(firstDigit); // Output: 1
Using Regular Expressions to find first digit in JavaScript
Regular expressions are patterns used to match character combinations in strings. In JavaScript, they can be used to match specific patterns within the string representation of a number, such as the first and last digits.
I would suggest to just take the absolute value for negative number case.
In following example, the regex pattern ^(-?\d)(.*?)(\d)$
matches the first and last digits of the number. The ^
and $
are start and end anchors, respectively. (-?\d)
captures the optional negative sign and the first digit, and (\d)
captures the last digit.
let number = Math.abs(-12345);
let [firstDigit, lastDigit] = number.toString().match(/^(.)(?:.*)(.)$/).slice(1);
console.log(firstDigit); // Output: "1"
console.log(lastDigit); // Output: "5"
Using String.match() and Array.pop() to find last digit in JavaScript
This approach combines the use of regular expressions with array manipulation. First, the String.match()
method is employed to create an array of all individual digits from the string representation of the number. Then, Array.pop()
is used to easily extract the last element from this array, which corresponds to the last digit of the number.
In this code, number.toString().match(/\d/g)
converts the number to a string and uses a regular expression to find all digit characters (\d
). The g
flag in the regular expression ensures that all instances of the digit characters in the string are matched and returned in an array. The pop()
method is then used on this array, which removes the last element from the array and returns it. Since the array contains the digits of the number in order, the last element removed and returned by pop()
is the last digit of the original number.
let number = Math.abs(-12345);
// Creates an array of individual digits
let digitsArray = number.toString().match(/\d/g);
// Removes and returns the last element of the array
let lastDigit = digitsArray.pop();
console.log(lastDigit); // Output: "5"
Tips & errors while extracting first and last digits in JavaScript
Handling Floating Point Numbers
- Methods that work well for integers may not apply directly to floating-point numbers.
- Convert floating-point numbers to strings or handle their integer and decimal parts separately.
- For decimal part, note that JavaScript can introduce imprecision due to floating point digits.
let floatNumber = 123.456;
let integerPart = Math.floor(floatNumber);
let decimalPart = floatNumber - integerPart;
// Handle integer and decimal parts separately if needed
Dealing with Very Large Numbers
- JavaScript’s
Number
type can lose precision with very large numbers. - Use
BigInt
for precise arithmetic with very large numbers.
let largeNumber = BigInt("123456789012345678901234567890");
let lastDigit = largeNumber % BigInt(10);
console.log(lastDigit); // Output: 0n (BigInt representation)
🧪Practice Coding Problem
Your turn now!😃 Lets test our understanding by solving a problem.
Write a JavaScript function that takes a number (positive or negative) and returns an object containing the first and last digits of that number.
Problem (JavaScript)function extractFirstAndLastDigit(number) { // > > > 👉 Write code here 👈 < < < } // Driver Code console.log(extractFirstAndLastDigit(12345)); // Should return { firstDigit: 1, lastDigit: 5 } console.log(extractFirstAndLastDigit(-9876)); // Should return { firstDigit: 9, lastDigit: 6 }
Please attempt before seeing the Answer:
function extractFirstAndLastDigit(number) {
let absNumber = Math.abs(number);
let lastDigit = absNumber % 10;
while (absNumber >= 10) {
absNumber = Math.floor(absNumber / 10);
}
let firstDigit = absNumber;
return { firstDigit, lastDigit };
}
Explanation:
Math.abs(number)
is used to handle negative numbers.absNumber % 10
extracts the last digit.- The
while
loop keeps dividingabsNumber
by 10 until it’s a single-digit number, which is the first digit. - The function returns an object containing both the first and last digits.
Now you are a pro in extracting first and last digits in JavaScript.
Keep learning, and keep coding! 🚀👨💻