first digit javascript

First Digit JavaScript

First digit JavaScript refers to the first number in a given numerical value. For example, if the number is 456, the first digit would be 4. There are multiple ways to extract the first digit in JavaScript, and I'll explain some of them below:

Method 1: Using Math.floor() and Math.abs()


let num = -1245;
let firstDigit = parseInt(Math.abs(num).toString()[0]);
console.log(firstDigit); // Output: 1

The above code uses the Math.abs() method to convert the given number to its absolute value, and then converts it to a string using toString(). The first character of the string (which corresponds to the first digit) is then extracted using the square bracket notation. Finally, parseInt() is used to convert the first character back to an integer.

Method 2: Using String.prototype.charAt()


let num = -1245;
let firstDigit = parseInt(num.toString().charAt(0));
console.log(firstDigit); // Output: 1

This code uses the toString() method to convert the given number to a string, and then uses charAt() to extract the first character (which corresponds to the first digit). Finally, parseInt() is used to convert the first character back to an integer.

Method 3: Using Math.log10() and Math.floor()


let num = 1245;
let firstDigit = parseInt(num / Math.pow(10, Math.floor(Math.log10(num))));
console.log(firstDigit); // Output: 1

This code uses the Math.log10() method to find the number of digits in the given number, and then uses Math.floor() to round down to the nearest integer. This gives us the exponent for the base-10 logarithm of the number. We then use Math.pow() to raise 10 to this exponent, which gives us the largest power of 10 that is less than or equal to the given number. Finally, we divide the given number by this power of 10 and use parseInt() to extract the first digit.

These are just a few ways to extract the first digit in JavaScript. Depending on your use case, one method may be more appropriate than the others. Experiment with each method and see which one works best for you!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe