Jump to content


Photo

resolving a fraction


  • Please log in to reply
2 replies to this topic

#1 earl_dc10

earl_dc10
  • Members
  • PipPipPip
  • Advanced Member
  • 71 posts

Posted 05 April 2006 - 09:43 PM

hey, I have a field where the user inputs a number, and it can be a fraction, I could have 2 fields where it's like <field> / <field> but I don't want to do that. I need to seperate the fraction ie (2/3 = 2, and 3) and I devised a way to do that :
for($x = 1; $x <= 100; $x++)
    {$temp = $input*$x;
    if(($temp/$x) == $input)
        {$num1 = $temp;
        $num2 = $x;
        break;
        }
    }

it only reads the first half of the fraction, if I were to multiply $input by $x, it does this:
input will be 2/3 and $x will be 3, you'd think the output would be 2, right? it comes out as 6, it ignores what is after the "/" is there any way to resolve the fraction? ie, 2/3 = .6666... and go from there? thanks!

-J
got a problem? Google helps many of those in need

#2 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 05 April 2006 - 10:27 PM

alright, this was an interesting question, so i did a little testing. first off, you can do this two ways. first, you can extract the numerator and denominator separately and THEN run the fraction:

$components = explode('/', $_POST['fraction']);
if (count($components) > 1)
{
  it's an array with $components[0] as numerator, $components[1] as denominator
}
else
{
  it's just a number
}

a warning about using this method: it isn't exceptionally good at error-checking. if the user puts in more than one slash, it will only use the first and second numbers if you use $components[0] and $components[1].

otherwise, you can use the eval() function to process the $_POST['fraction'] as though it were an actual statement:

eval("\$decimal = {$_POST['fraction']};");

if $_POST['fraction'] was "2/3" for example, what eval() would run is:

$decimal = 2/3;

which is what you're after. this also takes care of the case that the number is not a fraction, since $decimal will just be assigned to the number.

hope this helps.

#3 earl_dc10

earl_dc10
  • Members
  • PipPipPip
  • Advanced Member
  • 71 posts

Posted 05 April 2006 - 10:50 PM

thanks, that was exactly what I needed, also my "fraction finder" script shown above was extremely flawed notice
{$temp = $input*$x;
    if(($temp/$x) == $input)
// that was just stupid 
so I needed all the help I could get, thanks again!
got a problem? Google helps many of those in need




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users