Page 1 of 1

Want to Convert "1/2" to 0.5

Posted: Fri Dec 07, 2007 5:10 am
by urnetmate
Hi all,

I want to convert a string representation (1/2) to a float value as 0.5
Please help me to sort out the issue.

Thanks in advance ...
:(

Posted: Fri Dec 07, 2007 5:17 am
by VladSun

Code: Select all

$s = "1/2";
echo eval("return ".$s.";");
If $s gets its value from user input you must sanitize it before eval()!

thx buddy

Posted: Fri Dec 07, 2007 5:21 am
by urnetmate
thanks buddy,

i used the code this way,

Code: Select all

$tmp_str = "1/2";
eval("\$str = $tmp_str;");
echo $str;

Posted: Fri Dec 07, 2007 9:34 am
by John Cartwright
Please don't use eval.. if you do VERY careful when allowing user input to be executable :)

Code: Select all

$string = explode('/', '1/2');
echo $string[0] / $string[1])

Posted: Fri Dec 07, 2007 11:39 am
by Maugrim_The_Reaper
Is this you by any chance?

http://news.php.net/php.internals/33828

Suggestion to add an arithmetic string evaluator arith().

Posted: Fri Dec 07, 2007 1:59 pm
by nathanr
nah that was me, after reading this..!

8O

Posted: Fri Dec 07, 2007 3:13 pm
by Christopher
Safer:

Code: Select all

$equation = '1/2';
$string = explode('/', $equation);
$numerator = (int)trim($string[0]);
$denominator = (int)trim($string[1]);
$result =  $denominator == 0 ? 0 : $numerator / $denominator;
echo $result;