You are here

function commerce_currency_convert in Commerce Core 7

Converts a price amount from a currency to the target currency based on the current currency conversion rates.

The Commerce module establishes a default conversion rate for every currency as 1, so without any additional information there will be a 1:1 conversion from one currency to the next. Other modules can provide UI based or web service based alterations to the conversion rate of the defined currencies as long as every rate is calculated relative to a single base currency. It does not matter which currency is the base currency as long as the same one is used for every rate calculation.

To convert an amount from one currency to another, we simply take the amount value and multiply it by the current currency's conversion rate divided by the target currency's conversion rate.

Parameters

$amount: The numeric amount value of the price to be rounded.

$currency_code: The currency code for the current currency of the price.

$target_currency_code: The currency code for the target currency of the price.

Return value

The numeric amount value converted to its equivalent in the target currency.

7 calls to commerce_currency_convert()
commerce_line_items_total in modules/line_item/commerce_line_item.module
Returns the total price amount and currency of an array of line items.
commerce_line_item_unit_price_currency_convert in modules/line_item/commerce_line_item.rules.inc
Rules action: convert the unit price to a different currency.
commerce_order_calculate_total in modules/order/commerce_order.module
Calculates the order total, updating the commerce_order_total field data in the order object this function receives.
commerce_price_components_combine in modules/price/commerce_price.module
Combines the price components of two prices into one components array, merging all components of the same type into a single component.
commerce_price_component_total in modules/price/commerce_price.module
Returns the total value of components in a price array converted to the currency of the price array.

... See full list

File

./commerce.module, line 725
Defines features and functions common to the Commerce modules.

Code

function commerce_currency_convert($amount, $currency_code, $target_currency_code) {
  $currency = commerce_currency_load($currency_code);

  // Invoke the custom conversion callback if specified.
  if (!empty($currency['conversion_callback'])) {
    return $currency['conversion_callback']($amount, $currency_code, $target_currency_code);
  }
  $target_currency = commerce_currency_load($target_currency_code);

  // First multiply the amount to accommodate differences in decimals between
  // the source and target currencies.
  $exponent = $target_currency['decimals'] - $currency['decimals'];
  $amount *= pow(10, $exponent);
  return $amount * ($currency['conversion_rate'] / $target_currency['conversion_rate']);
}