You are here

public function IngredientQuantityUtility::getQuantityFromFraction in Recipe 8.2

Converts an ingredient's quantity from fraction to decimal.

Parameters

string $ingredient_quantity: The ingredient quantity formatted as a fraction.

Return value

float The ingredient quantity formatted as a decimal.

File

modules/ingredient/src/Utility/IngredientQuantityUtility.php, line 140

Class

IngredientQuantityUtility
Provides the ingredient.quantity service.

Namespace

Drupal\ingredient\Utility

Code

public function getQuantityFromFraction($ingredient_quantity) {

  // Replace a dash separated fraction with a ' ' to normalize the input
  // string.
  $ingredient_quantity = preg_replace('/^(\\d+)[\\-](\\d+)[\\/](\\d+)/', '${1} ${2}/${3}', $ingredient_quantity);
  if ($pos_slash = strpos($ingredient_quantity, '/')) {
    $pos_space = strpos($ingredient_quantity, ' ');

    // Can't trust $pos_space to be a zero value if there is no space
    // so set it explicitly.
    if ($pos_space === FALSE) {
      $pos_space = 0;
    }
    $whole = (int) substr($ingredient_quantity, 0, $pos_space);
    $numerator = (int) substr($ingredient_quantity, $pos_space, $pos_slash);
    $denominator = (int) substr($ingredient_quantity, $pos_slash + 1);
    $ingredient_quantity = $whole + $numerator / $denominator;
  }
  return $ingredient_quantity;
}