Convert exponential number to decimal in php

╄→尐↘猪︶ㄣ 提交于 2019-12-17 07:54:14

问题


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.


回答1:


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

Limitation of floating number & integer




回答2:


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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/4461444/convert-exponential-number-to-decimal-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!