user3440366
user3440366

Reputation: 21

Convert string to float in PHP

I have a string value like this "0.00050722" and I want to convert its data type to double/float.

I've been trying floatval() and doubleval() but it always returns me a value of 0.

I need to get the exact of amount of 0.00050722 in a float datatype.

Upvotes: 1

Views: 26196

Answers (2)

hoss
hoss

Reputation: 2458

You just need to (typecast) to the desired type

    <?php
    $string = "0.00050722";
    $float = (float) $string;
    $float2 = $string + 0.0; //this works as well.
    $floatval = floatval($string);
    $double = (double) $string;

    // TEST
    printf("string:   %s - %d<br>", $string, is_float ($string));
    printf("float :   %g - %d<br>", $float, is_float ($float));
    printf("float2:   %g - %d<br>", $float2, is_float ($float2));
    printf("floatval: %g - %d<br>", $floatval, is_float($floatval));
    printf("double:   %g - %d<br>", $string, is_double ($double));

?>

Should result in:

string:   0.00050722 - 0
float :   0.00050722 - 1
float2:   0.00050722 - 1
floatval: 0.00050722 - 1
double:   0.00050722 - 1

Notice that concatenation also works.

Upvotes: 5

Dexter
Dexter

Reputation: 1796

it's work's for me try this

<?php
    $string = "0.00050722";
    $num = floatval($string);
    echo $num;   // output 0.00050722
?>

Upvotes: 1

Related Questions