When PHP converts a number to string (for printing it out, for example), sometimes it may convert it to scientific notation out of nowhere (0.000021 for example). Or the number can be already in a string format with exponent. But most people prefer to see a conventional decimal number instead.
As it turned out, existing answers on Stack Overflow are expectedy short-sighted or at least incomplete, so I decided to try a complete universal solution. Not sure though if it covers all edge cases and if it can be improved in general.
Type hinting is intentionally left out for compatibility.
function scientific2decimal($num, $decimal_separator = ".", $thousands_separator = ",")
{
if (!preg_match('!\d+(\.(\d+))?e([+-]?)(\d+)$!i', $num, $matches)) {
return $num;
}
list(,,$decimals, $sign, $exponent) = $matches;
$sign = $sign ?: "+";
$actual_decimals = strlen($decimals);
if ($sign === '+') {
$number_of_decimals = max(0, $actual_decimals - $exponent);
} else {
$number_of_decimals = $exponent + $actual_decimals;
}
return number_format($num, $number_of_decimals, $decimal_separator, $thousands_separator);
}
a simple test:
$test = [
0.000021,
'1e3',
'1.1337228E-3',
'1.1337228E-6',
'1.0002E3',
'1.13372223434E+6',
'2.133333E-5',
];
foreach ($test as $num) {
echo $num, ": ", scientific2decimal($num), "\n";
}
return rtrim(rtrim(number_format(floatval($num), strlen($num), $decimal_separator, $thousands_separator), '0'), $decimal_separator);
\$\endgroup\$