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?
Fractions, Decimals, and Regexes
Moderator: General Moderators
look into preg_replace_callback and use something like '#\((\d+)/(\d+)\)#' as a pattern
- ambivalent
- Forum Contributor
- Posts: 173
- Joined: Thu Apr 14, 2005 8:58 pm
- Location: Toronto, ON
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:
Sorta like:
Code: Select all
$fraction = explode("/", $input);
$result = $fraction[0] / $fraction[1];
$result = sprintf("%.5f", $result);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
));
}