0

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?

9
  • Why do you need to do this? PHP understands scientific notation, so it will treat these as floats when you use them in mathmatical expressions. Commented Nov 14, 2013 at 6:08
  • I need to check if the float have less than 3 digital number, I write a function myself(expload the number by "."), however when it meets mathmatical expression, it doesn't work. Commented Nov 14, 2013 at 6:25
  • Why not just if ($number < 1000)? Commented Nov 14, 2013 at 6:26
  • sorry, i misspelled it....I mean at most 3 decimal digit. Commented Nov 14, 2013 at 6:30
  • 1
    @sectus well, your answer is great! Commented Nov 14, 2013 at 6:45

6 Answers 6

4

You can make use of floatval

<?php
echo floatval("1.0E+7").".00";//10000000.00
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

Your best bet is to cast it....

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

Comments

2

You can use floatval():

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

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

Comments

2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.