Yang
Yang

Reputation: 792

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?

Upvotes: 0

Views: 1399

Answers (6)

sectus
sectus

Reputation: 15464

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

Upvotes: 2

Veerendra
Veerendra

Reputation: 2622

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

Upvotes: 1

You can make use of floatval

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

Upvotes: 4

tslater
tslater

Reputation: 4432

Your best bet is to cast it....

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

Upvotes: 3

Sutandiono
Sutandiono

Reputation: 1750

You can use floatval():

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

printf ("%.02f", $fl);
// Result: 10000000.00

Upvotes: 2

5eeker
5eeker

Reputation: 1027

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
?> 

Upvotes: 3

Related Questions