function recipe_ingredient_quantity_from_decimal in Recipe 5
Same name and namespace in other branches
- 6 recipe.module \recipe_ingredient_quantity_from_decimal()
- 7.2 recipe.module \recipe_ingredient_quantity_from_decimal()
- 7 recipe.module \recipe_ingredient_quantity_from_decimal()
Converts an ingredient's quantity from decimal to fraction
2 calls to recipe_ingredient_quantity_from_decimal()
- recipe_form in ./
recipe.module - Implementation of hook_form().
- theme_node_recipe in ./
recipe.module - A custom theme function.
File
- ./
recipe.module, line 588 - recipe.module - share recipes for drupal 5.x
Code
function recipe_ingredient_quantity_from_decimal($ingredient_quantity) {
if (strpos($ingredient_quantity, '.') && variable_get('recipe_fraction_display', t('{%d} %d⁄%d'))) {
$decimal = $ingredient_quantity;
if ($decimal == 0) {
$whole = 0;
$numerator = 0;
$denominator = 1;
$top_heavy = 0;
}
else {
$sign = 1;
if ($decimal < 0) {
$sign = -1;
}
}
if (floor(abs($decimal)) == 0) {
$whole = 0;
$conversion = abs($decimal);
}
else {
$whole = floor(abs($decimal));
$conversion = abs($decimal);
}
$power = 1;
$flag = 0;
while ($flag == 0) {
$argument = $conversion * $power;
if ($argument == floor($argument)) {
$flag = 1;
}
else {
$power = $power * 10;
}
}
// workaround for thirds, sixths, ninths, twelfths
$overrides = array(
'3333' => array(
1,
3,
),
'6666' => array(
2,
3,
),
'9999' => array(
3,
3,
),
// thirds
'1666' => array(
1,
6,
),
'8333' => array(
5,
6,
),
// sixths
'1111' => array(
1,
9,
),
'2222' => array(
2,
9,
),
'4444' => array(
4,
9,
),
'5555' => array(
5,
9,
),
'7777' => array(
7,
9,
),
'8888' => array(
8,
9,
),
// ninths
'0833' => array(
1,
12,
),
'4166' => array(
5,
12,
),
'5833' => array(
7,
12,
),
'9166' => array(
11,
12,
),
);
$conversionstr = substr((string) ($conversion - floor($conversion)), 2, 4);
if (array_key_exists($conversionstr, $overrides)) {
if ($overrides[$conversionstr][0] == $overrides[$conversionstr][1]) {
return ($whole + 1) * $sign;
}
$denominator = $overrides[$conversionstr][1];
$numerator = floor($conversion) * $denominator + $overrides[$conversionstr][0];
}
else {
$numerator = $conversion * $power;
$denominator = $power;
}
$hcf = recipe_euclid($numerator, $denominator);
$numerator = $numerator / $hcf;
$denominator = $denominator / $hcf;
$whole = $sign * $whole;
$top_heavy = $sign * $numerator;
$numerator = abs($top_heavy) - abs($whole) * $denominator;
if ($whole == 0 && $sign == -1) {
$numerator = $numerator * $sign;
}
$ingredient_quantity = sprintf(variable_get('recipe_fraction_display', t('{%d} %d⁄%d')), $whole, $numerator, $denominator);
if ($whole == 0 && strpos($ingredient_quantity, '{') >= 0) {
/* remove anything in curly braces */
$ingredient_quantity = preg_replace('/{.*}/', '', $ingredient_quantity);
}
else {
/* remove just the curly braces, but keep everything between them */
$ingredient_quantity = preg_replace('/{|}/', '', $ingredient_quantity);
}
}
return filter_xss_admin($ingredient_quantity);
}