JavaScript – Get the first digit of a number

JavaScript – Get the first digit of a number

In this post we will give you information about JavaScript – Get the first digit of a number. Hear we will give you detail about JavaScript – Get the first digit of a numberAnd how to use it also give you demo for it if it is necessary.

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:

  1. Convert the number to a string.

  2. Call the charAt() method on it, by passing the first digit index 0.

  3. It returns the character at that index.

Here is an example:

const id = 13456;const firstDigit = String(id).charAt(0);// converting string back to numberconsole.log(Number(firstDigit));

Output:

1

The 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 numberconsole.log(Number(firstDigit));

Output:

1

Hope this code and post will helped you for implement JavaScript – Get the first digit of a number. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US