How to get the first digit of a float number in JavaScript

3 Answers

0 votes
function get_first_digit(first_digit) {
    while (first_digit >= 9)
        first_digit = Math.floor(first_digit / 10);
      
    return first_digit;
}
   
const f = 376.287152; 
   
console.log(get_first_digit(f)); 
    
     
/*
run:
      
3
         
*/
 

 



answered Aug 31, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
function get_first_digit(f) {
    let n = Math.floor(f);
     
    const total_digits_minus_one = Math.floor(Math.log10(n)); 
    
    n = Math.floor(n / Math.pow(10, total_digits_minus_one)); 
     
    return n;
}
  
 
const f = 376.287152; 
  
console.log(get_first_digit(f)); 


/*
run:
     
3
        
*/
   

 



answered Aug 31, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
function getFirstDigit(n) {
    return parseInt(n.toString().substring(0, 1));
}

const f = 376.287152;
const first_digit = getFirstDigit(f);

console.log(first_digit);   



/*
run:
     
3
        
*/
   

 



answered Aug 31, 2019 by avibootz
edited Sep 15 by avibootz
...