function units_convert in Units of Measurement 7
Convert value measured in one unit into value measured in another unit.
Parameters
float $value: Value to be converted
string $from: Units in which $value is measured. Supply machine-readable name of the unit
string $to: Units in which $value needs to be converted. Supply machine-readable name of the unit
string $measure: Optional. Measure of value to be converted, normally the measure is looked up using the provided $form and $to, but in case the same unit measure is used in different measures, this parameter may narrow down unit measures to necessary scope of the supplied measure.
Return value
float Value $value, converted from $from units into $to units
1 call to units_convert()
- UnitsWebTestCase::testConvert in ./
units.test  - Testing unit conversion correctness.
 
File
- ./
units.module, line 117  - Provide API for managing and converting units of measurement.
 
Code
function units_convert($value, $from, $to, $measure = NULL) {
  if ($from == $to) {
    // That's an easy one. Value converting from a unit into the same unit
    // always will be the same value.
    return $value;
  }
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'units_unit')
    ->propertyCondition('machine_name', array(
    $from,
    $to,
  ));
  if (!is_null($measure)) {
    $query
      ->entityCondition('bundle', $measure);
  }
  $result = $query
    ->execute();
  if (!isset($result['units_unit']) || count($result['units_unit']) != 2) {
    // Probably wrong $from and/or $to were supplied, otherwise we would have
    // got exactly 2 results.
    return FALSE;
  }
  // Loading entities.
  $entities = units_unit_load_multiple(array_keys($result['units_unit']));
  foreach ($entities as $entity) {
    switch ($entity->machine_name) {
      case $from:
        $from = $entity;
        break;
      case $to:
        $to = $entity;
        break;
    }
  }
  if ($from->measure != $to->measure) {
    // The found units are from different measures. That's not okay.
    return FALSE;
  }
  // Loading measure.
  $measure = units_measure_machine_name_load(field_extract_bundle('units_unit', $from));
  $plugin = units_get_converter($measure->converter);
  if (!$plugin) {
    return FALSE;
  }
  $function = ctools_plugin_get_function($plugin, 'convert callback');
  if (!$function) {
    return FALSE;
  }
  return $function($value, $from, $to);
}