Fractions, Decimals, and Regexes

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
PnHoPob
Forum Newbie
Posts: 16
Joined: Thu Nov 10, 2005 7:16 pm

Fractions, Decimals, and Regexes

Post 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?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

look into preg_replace_callback and use something like '#\((\d+)/(\d+)\)#' as a pattern
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Post 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);
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post 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
	));

}
Post Reply