earl_dc10 Posted April 5, 2006 Share Posted April 5, 2006 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 Link to comment https://forums.phpfreaks.com/topic/6689-resolving-a-fraction/ Share on other sites More sharing options...
akitchin Posted April 5, 2006 Share Posted April 5, 2006 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. Link to comment https://forums.phpfreaks.com/topic/6689-resolving-a-fraction/#findComment-24304 Share on other sites More sharing options...
earl_dc10 Posted April 5, 2006 Author Share Posted April 5, 2006 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! Link to comment https://forums.phpfreaks.com/topic/6689-resolving-a-fraction/#findComment-24309 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.