How to get the first digit of float number in PHP

3 Answers

0 votes
$f = 239.5876;

$s = sprintf("%.4f", $f); 
    
echo $s[0];



  
/*
run:

2

*/

 



answered Aug 31, 2019 by avibootz
edited Aug 31, 2019 by avibootz
0 votes
function get_first_digit($f) {
    $first_digit = $f;

    while ($first_digit >= 9) {
        $first_digit = (int)($first_digit / 10);
    }
    
    return $first_digit;
}
  

$f = 761.7261;
  
echo get_first_digit($f);



  
/*
run:

7

*/

 



answered Aug 31, 2019 by avibootz
edited Aug 31, 2019 by avibootz
0 votes
function get_first_digit($f) {
    $total_digits_minus_one = (int)log10($f);

    $first_digit = (int)($f / pow(10, $total_digits_minus_one)); 
    
    return $first_digit;
}
  

$f = 9618.7261;
  
echo get_first_digit($f);



  
/*
run:

9

*/

 



answered Aug 31, 2019 by avibootz

Related questions

1 answer 155 views
1 answer 168 views
5 answers 407 views
1 answer 160 views
...