PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
urnetmate
Forum Commoner
Posts: 27 Joined: Wed Sep 27, 2006 1:09 am
Post
by urnetmate » Fri Dec 07, 2007 5:10 am
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 ...
VladSun
DevNet Master
Posts: 4313 Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria
Post
by VladSun » Fri Dec 07, 2007 5:17 am
Code: Select all
$s = "1/2";
echo eval("return ".$s.";");
If $s gets its value from user input you must sanitize it before eval()!
There are 10 types of people in this world, those who understand binary and those who don't
urnetmate
Forum Commoner
Posts: 27 Joined: Wed Sep 27, 2006 1:09 am
Post
by urnetmate » Fri Dec 07, 2007 5:21 am
thanks buddy,
i used the code this way,
Code: Select all
$tmp_str = "1/2";
eval("\$str = $tmp_str;");
echo $str;
John Cartwright
Site Admin
Posts: 11470 Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:
Post
by John Cartwright » Fri Dec 07, 2007 9:34 am
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])
nathanr
Forum Contributor
Posts: 200 Joined: Wed Jun 07, 2006 5:46 pm
Post
by nathanr » Fri Dec 07, 2007 1:59 pm
nah that was me, after reading this..!
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Fri Dec 07, 2007 3:13 pm
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;
(#10850)