Andy Groff
Andy Groff

Reputation: 2670

Converting a string to float in php

I'm getting some benchmark data about page execution time. Its provided by the framework as a string. I want to convert it into a float, multiply it by 1000, and store it in the DB as an int. It seems to be acting really strange and I was hoping someone can help me figure out why. Here is the code:

    $elapsed = $this->benchmark->elapsed_time();
    var_dump("before:");
    var_dump($elapsed);

    $elapsed = floatval($elapsed);

    var_dump("after:");
    var_dump($elapsed);

Here is the result:

string 'before:' (length=7) string '0.7608' (length=14) string 'after:' (length=6) float 0

EDIT: I figured this out thanks to someone pointing out that the string length was wrong. Apparently the method is returning the string '{elapsed_time}', the framework is buffering the output, and then replacing that string with the final eval time. Thanks for the help.

Upvotes: 0

Views: 4092

Answers (5)

tereško
tereško

Reputation: 58454

<?php

    $time = '0.5643';
    var_dump( $time );        
    //output  :: string(6) "0.5643"
    var_dump( $time * 1000 ); 
    //output  :: float(564.3)
?>

Everything as expected .. but then you do something really stupid like this:

<?php

    $badtime = "\0\0\0\0\0\0\0\0" . $time;
    var_dump( $badtime );        
    //output  :: string(14) "0.5643"

    var_dump($badtime * 1000); 
    //output  :: int(0)

    $goodtime = str_replace("\0", "", $badtime);
    var_dump($goodtime * 1000);
    //output  :: float(564.3)

?>

Upvotes: 1

Question Mark
Question Mark

Reputation: 3606

It could be that $this->benchmark->elapsed_time() is prepending a load of junk before the float, which would be why 0.7608 is 14 chars as minitech pointed out.

try:

$elapsed = floatval(trim($elapsed));

or

$elapsed = floatval(preg_replace('/[^0-9\.]/', '', $elapsed));

Bit of an odd one but the above may help, i'm not certain.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146269

$elapsed = ((float)$this->benchmark->elapsed_time()) * 1000;

Upvotes: 2

Oswaldo Acauan
Oswaldo Acauan

Reputation: 2740

<?php var_dump((float)'0.734' * 1000); //float(734) ?>

Upvotes: 1

core1024
core1024

Reputation: 1882

Not sure, but $elapsed *= 1000; should be fine.

Upvotes: 1

Related Questions