Shaun Stevens
Shaun Stevens

Reputation: 63

convert string to number not working

OK, this is driving me crazy, should be straightforward but I keep getting the result 0

$string="92.14";
$numericstring=(int)$string;
echo $numericstring; // get 0, should get 92.14

What am I missing - also tried (double) and floatval, same result..

Upvotes: 0

Views: 2098

Answers (3)

Shaun Stevens
Shaun Stevens

Reputation: 63

turns out that the string contained '' which I couldnt see in the editor i was looking at the string in, of course removing that allowed me to easily perform the math

Upvotes: 0

Med Abida
Med Abida

Reputation: 1222

your code worked fine for me, please check if you correctly added the <?php ?> if you're sure that everything is ok try using this code

<?php
$string="92.14";
$numericstring=intval($string);
echo $numericstring;
?>

but according to the result you expected the code above or you code will echo 92 NOT 92.14, so use floatval instead of intval like so:

<?php
$string="92.14";
$numericstring=floatval($string);
echo $numericstring;
?>

if none of this worked for you try adding trim() function to be sure that your string contain no spaces, (as suggested @Alejandro Iván)

<?php
$string="92.14";
$numericstring=floatval(trim($string));
echo $numericstring;
?>

let me know if you need more help

Upvotes: 1

ivcandela
ivcandela

Reputation: 331

to parse an integer

intval($string) //Output: 92

to parse a float (your case)

floatval($string); //Output: 92.14

Upvotes: 0

Related Questions