does php have a function that parses exponents in strings (eg: “9.5367431640625e-05”) or does it have to be done manually via regexp etc?

StackOverflow https://stackoverflow.com/questions/7271091

  •  18-01-2021
  •  | 
  •  

Question

does php have a function that will convert a string (data type will be string since its parsed from an external source) like:

string(..) "9.5367431640625e-05"

and perform the exponent calculations on said string and return the calculated value?

or do i need to use regexp etc style way to do something like:

9.5367431640625e-05 -> 9.5367431640625^-5 = calculated value

if php does not have such a function, best ideas on how to accomplish this? i was just going to pattern match something like

/^([0-9\.\-]+)e([0-9\.\-]+)$/

any better ideas?

thanks!

Was it helpful?

Solution

You could do a simple cast:

$float = (float)$string;

But besides checking for 0 (which might be a valid value ...) there is no way for error checking. You could also use the floatval() function which does the same.

But usually you won't have to do it as PHP will cast as needed. Mind that chapter of the documentation: http://de.php.net/manual/en/language.types.type-juggling.php

OTHER TIPS

Do a cast:

$float  = (float) $string;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top