JavaScript - Get the first digit of a number
In this tutorial, we will learn how to get the first of a number in JavaScript.
Getting the first digit of a number
To get the first digit of a number:
-
Convert the number to a string.
-
Call the
charAt()method on it, by passing the first digit index0. -
It returns the character at that index.
Here is an example:
const id = 13456;
const firstDigit = String(id).charAt(0);
// converting string back to number
console.log(Number(firstDigit));Output:
1The charAt() method accepts the character index as an argument and return its value in the string.
Similarly, we can also use the square brackets notation [] in JavaScript to get the first digit of a number.
Here is an example:
const id = 13456;
const firstDigit = String(id)[0];
// converting string back to number
console.log(Number(firstDigit));Output:
1

