R
R
Rsah2018-02-04 18:48:21
PHP
Rsah, 2018-02-04 18:48:21

Working with long float in php. How to improve the script?

Hello. Help advice.
I am requesting some values ​​from the cloud base. Numbers come back in scientific notation as a string "-2.726754802539826e+001" (number example).
The task is to convert these numbers into fixed-point numbers, rounded to 14 decimal places or less, such as "-2.72679480253983" (modified example) or "0.001233" or "1444.3" (if we take other numbers as a basis)
I have doubts that my code is bike:

if (is_numeric($value)) {
    $needle   = 'e';

    if(strripos($value, $needle) === false){
        $value =(int)$value;
    }else{
        $chunks = explode($needle, $value);
        $value = $chunks[0];
        $mantissa = (int)$chunks[1];

        $chunks = explode('.', $value);
        $integer = $chunks[0];

        $isNegative = false;
        if ($integer < 0){
            $isNegative = true;
            $integer = abs($integer);
        }

        $fractional = $chunks[1];
        if ($integer == 0 && $fractional == 0) {
            $value =(int)$value;
        }else{
            // shift numbers with $mantissa
            if ($mantissa > 0) {
                //saving number for transfer into $integer
                $trans = substr($fractional, 0, $mantissa);

                $fractional = substr($fractional, $mantissa);
                $integer = $integer . $trans;
            } elseif ($mantissa < 0){
                $integer = str_repeat("0", abs($mantissa)) . $integer;

                $trans = substr($integer, $mantissa);

                $integer = substr($integer,0, $mantissa);
                $fractional = $trans . $fractional;
            }

            $fractional = intval(round($fractional, -1));
            $value = $integer . "." . $fractional;

            // removing all zeros
            $value = trim($value, "0");

            // if $integer is 0
            if($value{0} == "."){
                $value = "0" . $value;
            }

            // removing excess dot if $fractional is 0
            if(substr($value, -1) ==  "."){
                $value = substr($value,0, -1);
            }

            if($isNegative){
                $value = "-" . $value;
            }
        }
    }
}

I will be glad to any ideas!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
OKyJIucT, 2018-02-04
@OKyJIucT

$val = -2.726754802539826e+001;
echo round($val, 14); // -27.267548025398

B
Boris Korobkov, 2018-02-04
@BorisKorobkov

Have you tried reading the documentation ?
echo (float) "-2.726754802539826e+001";prints -27.267548025398

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question