Convert exponential number to decimal in php

I have a floating point number in exponential format i.e. 4.1595246940817E-17 and I want to convert it into decimal number like 2.99 etc.

Any help will be appreciated.

format_number() sprintf() don't seem to be working for me.


You need a better math extension like BC Math, GMP... to handle the more precise precision.

Limitation of floating number & integer


Using the BC Math library you can bcscale() the numbers to a predetermined decimal, which sets the parameter for future calculations that require arithmetic precision.

bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

You could remove the decimal point ($x is your number):

$strfloat = strtolower((string)($x));
$nodec = str_replace(".", "", $x);

Then extract the exponential part.

list($num, $exp) = explode("e", $nodec);
$exp = intval($exp);

Then you have the decimal, and the number, so you can format it:

if($exp < 0) return "0." . ("0" * -($exp + 1)) . $num;
if($exp == 0) return (string)$x;
if($exp > 0) return $num . ("0" * $exp);

This doesn't add precision though, just extra zeroes.


Here's a solution using BC Math, as suggested by ajreal and Russell Dias:

$au = 65536; 
$auk = bcdiv($au, 1024);
$totalSize = bcdiv(bcmul(49107, $auk), bcpow(1024, 2), 2); 
echo $totalSize . "\n"; 

// echos 2.99