简体   繁体   中英

how to use PHP to convert numerical string to float?

I got a string

    "1.0E+7"

And i hope convert it to a float

    10000000.00

Is there any php functions do this job? Or I should do this conversion myself?

Further more, I will receive many strings like this, some are numerical and some are in scientific format, how can I convert all of them correctly without knowing the content?

You can make use of floatval

<?php
echo floatval("1.0E+7").".00";//10000000.00

Try this example for converting your string var into float type:

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?> 

Your best bet is to cast it....

$val ="1.0E+7"
(float) $val

Try this

// type casting
var_dump((float) "1.0E+7");   // float(10000000)
// type juggling
var_dump("1.0E+7" + 0.0);     // float(10000000)
// function 
var_dump(floatval("1.0E+7")); // float(10000000)

// other stuff
var_dump(round("1.0E+7"));    // float(10000000)
var_dump(floor("1.0E+7"));    // float(10000000)
var_dump(ceil("1.0E+7"));     // float(10000000)
var_dump(abs("1.0E+7"));      // float(10000000) 

// weird
var_dump(unserialize("d:"."1.0E+7".";")); // float(10000000) 
var_dump(json_decode('1.0E+7')); // float(10000000) 

And read type juggling , string conversion to numbers , floatval

You can use floatval() :

$num = "1.0E+7";
$fl = floatval ($num);

printf ("%.02f", $fl);
// Result: 10000000.00
<?php
$var = '1.0E+7';
$float_value_of_var = floatval($var);
printf ("%.02f", $float_value_of_var);
// 10000000.00
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM