1

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.

emcconville
  • 23,800
  • 4
  • 50
  • 66
user3440366
  • 21
  • 1
  • 1
  • 2
  • 1
    This question has already been asked : http://stackoverflow.com/q/481466/785207 `$float = (float) $value;` – Sparkup Mar 20 '14 at 03:42
  • 2
    `floatval` works fine for me. Show your code. – Barmar Mar 20 '14 at 03:42
  • 1
    @Sparkup If `floatval($value)` isn't working for him, `(float)$value` probably won't either. – Barmar Mar 20 '14 at 03:44
  • Probably :) I may have been a bit hasty in reading the details. – Sparkup Mar 20 '14 at 03:53
  • floatval($value); and $float = (float)$value; both are working. There must be some other problem in your code. Please ckeck carefully. – Rolen Koh Mar 20 '14 at 03:58
  • **THIS IS DEFINITELY NOT A DUPLICATE!** When casting to float fails like this and keeps giving you 0, then first check your locale (see PHP docs for setlocale) and if that fails, make sure your input isn't in some unexpected charset. I wasted hours trying to parse floats from an UTF16 input file in an UTF8 installation. – Fasermaler Apr 17 '17 at 10:31

2 Answers2

5

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.

hoss
  • 2,430
  • 1
  • 27
  • 42
1

it's work's for me try this

<?php
    $string = "0.00050722";
    $num = floatval($string);
    echo $num;   // output 0.00050722
?>
Dexter
  • 1,804
  • 4
  • 24
  • 53