How to get the first digit of 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;
}
 

var f = 376.287152; 
 
document.write(get_first_digit(f)); 
      
       
  
   
/*
run:
    
3
       
*/

 



answered Aug 31, 2019 by avibootz
0 votes
function get_first_digit(f) {
    var n = Math.floor(f);
    
    var total_digits_minus_one = Math.floor(Math.log10(n)); 
   
    n = Math.floor(n / Math.pow(10, total_digits_minus_one)); 
    
    return n;
}
 

var f = 376.287152; 
 
document.write(get_first_digit(f)); 
      
       
  
   
/*
run:
    
3
       
*/

 



answered Aug 31, 2019 by avibootz
0 votes
var f = 376.287152; 
 
var s = f.toString();
 
document.write(s[0]); 
      
       
  
   
/*
run:
    
3
       
*/

 



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