Jump to content

Archived

This topic is now archived and is closed to further replies.

earl_dc10

resolving a fraction

Recommended Posts

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 :
[code]
for($x = 1; $x <= 100; $x++)
    {$temp = $input*$x;
    if(($temp/$x) == $input)
        {$num1 = $temp;
        $num2 = $x;
        break;
        }
    }
[/code]

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

Share this post


Link to post
Share on other sites
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:

[code]$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
}[/code]

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:

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

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

[code]$decimal = 2/3;[/code]

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.

Share this post


Link to post
Share on other sites
thanks, that was exactly what I needed, also my "fraction finder" script shown above was extremely flawed notice
[code]
{$temp = $input*$x;
    if(($temp/$x) == $input)
// that was just stupid
[/code]
so I needed all the help I could get, thanks again!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.