How to get the first digit after the decimal point of a float number in PHP

2 Answers

0 votes
function first_decimal_digit(float $f): int {
    $s = sprintf("%.4f", $f);          // format to 4 decimals
  
    return (int)$s[strrpos($s, ".") + 1];
}

$f = 23.5876;
echo first_decimal_digit($f);


/*
run:

5

*/

 



answered Aug 31, 2019 by avibootz
edited Sep 16 by avibootz
0 votes
function first_decimal_digit(float $f): int {
    return (int)(floor(abs($f) * 10)) % 10;
}

$f = 23.6876;
echo first_decimal_digit($f);


/*
run:

6

*/

 



answered Aug 31, 2019 by avibootz
edited Sep 16 by avibootz

Related questions

...