Convert exponential number to decimal in php

前端 未结 4 1851
被撕碎了的回忆
被撕碎了的回忆 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: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.

提交回复
热议问题