Convert exponential number to decimal in php

前端 未结 4 1843
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 15:28

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

相关标签:
4条回答
  • 2020-11-30 15:49

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

    Limitation of floating number & integer

    0 讨论(0)
  • 2020-11-30 15:50

    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.

    0 讨论(0)
  • 2020-11-30 15:53

    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
    
    0 讨论(0)
  • 2020-11-30 16:02

    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
    
    0 讨论(0)
提交回复
热议问题