Page 1 of 1

Fractions, Decimals, and Regexes

Posted: Wed Nov 16, 2005 3:41 pm
by PnHoPob
I'm writing this code that needs to preg_replace any fraction into a terminating decimal under 5 digits. For example, I need to replace:
(1/2) by .5 1 digit
(1/8) by .125, etc. 3 digits

but

not (1/3), since it's .333333333 repeating
not (2/3), since it's .666666666, etc. repeating

How can I regex that?

Posted: Wed Nov 16, 2005 4:52 pm
by Weirdan
look into preg_replace_callback and use something like '#\((\d+)/(\d+)\)#' as a pattern

Posted: Wed Nov 16, 2005 5:08 pm
by ambivalent
If you know that the value is going to be in the format "1/2", could you not instead explode() it with the "/" as the delimiter and then do the division?

Sorta like:

Code: Select all

$fraction = explode("/", $input);

$result = $fraction[0] / $fraction[1];

$result = sprintf("%.5f", $result);

Posted: Wed Nov 16, 2005 5:32 pm
by sweatje
Here is something written as a SimpleTest test:

Code: Select all

function testReplaceRationalFunctions() {
$text = 'replace this 1/8 fraction and 1/2 this one but not 1/3';
$target = 'replace this 0.125 fraction and 0.5 this one but not 1/3';

$this->assertEqual(
	$target
	,preg_replace_callback(
		'~\b(\d+)/(\d+)\b~'
		,create_function(
			'$m'
			,'$ret = $m[1] / $m[2]; return (strlen($ret)>6) ? $m[0] : $ret;'
		)
		,$text
	));

}