Convert a string containing a number in scientific notation to a double in PHP
Asked Answered
B

8

17

I need help converting a string that contains a number in scientific notation to a double.

Example strings: "1.8281e-009" "2.3562e-007" "0.911348"

I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?

Bedsore answered 2/1, 2011 at 3:11 Comment(0)
R
18

PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).

In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).

Try for instance

  foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
  {
    echo "String $a: Number: " . ($a + 1) . "\n";
  }

just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.

Result:

  String 1.8281e-009: Number: 1.0000000018281
  String 2.3562e-007: Number: 1.00000023562
  String 0.911348:    Number: 1.911348

You might also cast the result using (float)

  $real = (float) "3.141592e-007";
Ratal answered 2/1, 2011 at 3:18 Comment(7)
It's not typeless. You can still distinguish between (for example) strings and ints with is_string and is_int. It's dynamically typed, with a lot of implicit conversions. Other than that, this is a good answer.Tartaglia
oh, didn't know php understands scientific notation. This is exactly what I needed. ThanksBedsore
@Matthew I said programming wise. When programming, you do not have specifically to care about the types. Of course, internally PHP stores types. Dynamically typed is more appropriate - but I'm not sure a beginner will understand that definition better.Hemianopsia
you still sometimes need to distinguish when programming ordinary PHP code. For instance, a function might use is_array to test a parameter, and throw an exception if it's false.Tartaglia
@Matthew agreed, and I edited the answer. The typeless is by opposition to C for instance, where all objects have to be clearly and definitely associated to a type.Hemianopsia
-1, your solution loses precision. Casting to float is more accurate.Angelineangelique
Would it still lose precision if you do "1.8281e-009" + 0?Redeem
D
11
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Doviedow answered 2/1, 2011 at 3:36 Comment(0)
M
9

Following line of code can help you to display bigint value,

$token=  sprintf("%.0f",$scienticNotationNum );

refer with this link.

Myotonia answered 7/2, 2013 at 11:1 Comment(0)
V
6
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer) {
    // this is a whole number, so remove all decimals
    $output = $integer;
} else {
    // remove trailing zeroes from the decimal portion
    $output = rtrim($float,'0');
    $output = rtrim($output,'.');
}
Violist answered 26/7, 2012 at 10:43 Comment(0)
H
4

I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:

Example from the post:

$big_integer = 1202400000; 
$formatted_int = number_format($big_integer, 0, '.', ''); 
echo $formatted_int; //outputs 1202400000 as expected 
Hulsey answered 13/6, 2013 at 15:42 Comment(1)
What if integer is 111776395101 and formated int is 1.11776E+11, Above solution doesn't return correct number.Broadleaf
D
4

Use number_format() and rtrim() functions together. Eg

//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros

I created a function, with more functions (pun not intended)

function decimalNotation($num){
    $parts = explode('E', $num);
    if(count($parts) != 2){
        return $num;
    }
    $exp = abs(end($parts)) + 3;
    $decimal = number_format($num, $exp);
    $decimal = rtrim($decimal, '0');
    return rtrim($decimal, '.');
}
Detachment answered 13/11, 2017 at 21:11 Comment(0)
S
3
function decimal_notation($float) {
        $parts = explode('E', $float);

        if(count($parts) === 2){
            $exp = abs(end($parts)) + strlen($parts[0]);
            $decimal = number_format($float, $exp);
            return rtrim($decimal, '.0');
        }
        else{
            return $float;
        }
    }

work with 0.000077240388

Sharlenesharline answered 30/12, 2017 at 19:58 Comment(0)
H
1

I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar

Hydrophilous answered 16/2, 2020 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.