How to get the first digit of int number in JavaScript

5 Answers

0 votes
const n = 87236;
 
const s = n.toString();
 
console.log(s[0]); 
       
        
   
    
/*
run:
     
8
        
*/

 



answered Aug 31, 2019 by avibootz
edited Apr 16, 2024 by avibootz
0 votes
const n = 87236;
 
const s = n.toString();

let number = s[0] - '0';
 
console.log(number); 
       
        
   
    
/*
run:
     
8
        
*/

 



answered Aug 31, 2019 by avibootz
edited Apr 16, 2024 by avibootz
0 votes
const n = 87236;
 
let first_digit = n;
   
while (first_digit >= 10) {
    first_digit = Math.floor(first_digit / 10);
}
 
console.log(first_digit); 
       
        
   
    
/*
run:
     
8
        
*/

 



answered Aug 31, 2019 by avibootz
edited Apr 16, 2024 by avibootz
0 votes
const n = 87236;
 
const firstDigitStr = String(n)[0];
 
console.log(firstDigitStr); 
       
        
   
    
/*
run:
     
8
        
*/

 



answered Apr 16, 2024 by avibootz
0 votes
function getFirstDigit(num) {
    return Number(String(num)[0]);
}

const n = 87236;
 
let first_digit = getFirstDigit(n)
 
console.log(first_digit); 
       
        
   
    
/*
run:
     
8
        
*/

 



answered Apr 16, 2024 by avibootz

Related questions

...