Want to Convert "1/2" to 0.5

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

Post Reply
urnetmate
Forum Commoner
Posts: 27
Joined: Wed Sep 27, 2006 1:09 am

Want to Convert "1/2" to 0.5

Post 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 ...
:(
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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()!
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

thx buddy

Post by urnetmate »

thanks buddy,

i used the code this way,

Code: Select all

$tmp_str = "1/2";
eval("\$str = $tmp_str;");
echo $str;
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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])
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post 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().
User avatar
nathanr
Forum Contributor
Posts: 200
Joined: Wed Jun 07, 2006 5:46 pm

Post by nathanr »

nah that was me, after reading this..!

8O
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post 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;
(#10850)
Post Reply