How to get the first and the last digit of a number in JavaScript

4 Answers

0 votes
const number = 87354;
  
let firstDigit = number;
while (firstDigit >= 10) {
     firstDigit /= 10; 
}
firstDigit = Math.trunc(firstDigit);
console.log(firstDigit);
   
const lastDigit = number % 10;
console.log(lastDigit);
 
 
 
/*
run:
 
8
4
 
*/

 



answered Jun 3, 2020 by avibootz
edited Oct 29, 2024 by avibootz
0 votes
const number = 87354;
   
const numberStr = number.toString();
const firstDigit = numberStr[0];
console.log(firstDigit);
    
const lastDigit = numberStr[numberStr.length - 1];
console.log(lastDigit);
 
  
/*
run:
  
8
4
  
*/

 



answered Oct 29, 2024 by avibootz
edited Oct 29, 2024 by avibootz
0 votes
function getFirstDigit(number) {
    number = Math.abs(number);
     
    while (number >= 10) {
        number = Math.floor(number / 10);
    }
     
    return number;
}
 
const number = 87354;
   
const firstDigit = getFirstDigit(number);
console.log(firstDigit);
    
const lastDigit = number % 10;
console.log(lastDigit);
 
  
/*
run:
  
8
4
  
*/

 



answered Oct 29, 2024 by avibootz
edited Oct 29, 2024 by avibootz
0 votes
const number = 87354;
   
const firstDigit = Math.floor(number / Math.pow(10, Math.floor(Math.log10(number))));
console.log(firstDigit);
 
const lastDigit = number % 10;
console.log(lastDigit);
 
  
/*
run:
  
8
4
  
*/

 



answered Oct 29, 2024 by avibootz
edited Oct 29, 2024 by avibootz

Related questions

1 answer 217 views
1 answer 197 views
1 answer 100 views
1 answer 108 views
1 answer 96 views
1 answer 80 views
...