Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``

        If ``date`` is omitted then the date given by ``money.date`` will be used.
513768
def convert(self, money, to_currency, date=None):
        
        if str(money.currency) == str(to_currency):
            return copy.copy(money)
        return Money(
            amount=money.amount
            * self.rate(money.currency, to_currency, date or datetime.date.today()),
            currency=to_currency,
        )
34462
def get_exchange_rate(self, base, target, raise_errors=True):
        """"""
        assert base and target

        base, target = base.lower(), target.lower()

        r = self.session.get(API_SIMPLE_TICKER.format(base, target))
        if r.status_code != requests.codes.ok:
            if not raise_errors:
                return None
            raise CryptonatorException(
                ("An error occurred while getting requested exchange rate "
                 "({} from Cryptonator).").format(r.status_code)
            )

        j = r.json()
        if not j['success'] or j['error']:
            if not raise_errors:
                return None
            raise CryptonatorException(
                ("An error occurred while getting requested exchange rate ({}, {})"
                 "('{}').").format(base, target, j['error'])
            )

        return float(j['ticker']['price'])
617676
def loads(cls, s: str) -> 'Money':
        """"""
        try:
            currency, amount = s.strip().split()
            return cls(amount, currency)
        except ValueError as err:
            raise ValueError("failed to parse string "
                             " '{}': {}".format(s, err))
480671
def get_rate_for(self, currency: str, to: str, reverse: bool=False) -> Number:
        """"""

        # Return 1 when currencies match
        if currency.upper() == to.upper():
            return self._format_number('1.0')

        # Set base and quote currencies
        base, quote = currency, to
        if reverse:
            base, quote = to, currency

        try:  # Get rate from source
            rate = self._get_rate(base, quote)
        except Exception as e:
            raise ConverterRateError(self.name) from e

        # Convert rate to number
        rate = self._format_number(rate)

        try:  # Validate rate value
            assert isinstance(rate, (float, Decimal))
            assert rate > 0
        except AssertionError as e:
            raise ConverterValidationError(self.name, rate) from e

        # Return market rate
        if reverse:
            return self._format_number('1.0') / rate
        return rate
335271
def rate(self, currency):
        """"""
        if not self._backend:
            raise ExchangeBackendNotInstalled()
        return self._backend.rate(currency)
1110440
def convert_to_btc_on(self, amount, currency, date_obj):
        
        if isinstance(amount, Decimal):
            use_decimal = True
        else:
            use_decimal = self._force_decimal

        start = date_obj.strftime('%Y-%m-%d')
        end = date_obj.strftime('%Y-%m-%d')
        url = (
            'https://api.coindesk.com/v1/bpi/historical/close.json'
            '?start={}&end={}&currency={}'.format(
                   start, end, currency
               )
        )
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            price = data.get('bpi', {}).get(start, None)
            if price:
                if use_decimal:
                    price = Decimal(price)
                try:
                    converted_btc = amount/price
                    return converted_btc
                except TypeError:
                    raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
        raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date")
323262
public void setCurrency(String currency) {
		currency = StringUtils.upperCase(currency);
		if (!CurrencyUtils.getInstance().isValidCurrency(currency)) {
			currency = "EUR";
		}
		this.currency = currency;
	}
165315
private function retrieveExchangeRateFor(Currency $currency): void
    {
        $conversion = sprintf('%s_%s', $this->baseCurrency->getCode(), $currency->getCode());

        $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/api/v6/convert', [
            'query' => ['q' => $conversion]
        ]);

        $data = json_decode($response->getBody(), true);

        if (! array_key_exists($conversion, $data['results'])) {
            throw CurrencyConverterApiException::currencyNotFound($currency->getCode());
        }

        $this->exchangeRates[$currency->getCode()] = (float) $data['results'][$conversion]['val'];
    }
1097405
def convert_using_api(from_currency, to_currency):
	
	convert_str = from_currency + '_' + to_currency
	options = {'compact': 'ultra', 'q': convert_str}
	api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
	result = requests.get(api_url, params=options).json()
	return result[convert_str]
1275786
def setCurrency( self, currency ):
        
        self._currency = currency
        self.setValue(self.value())
502115
def convert(amount, from_code, to_code, decimals=2, qs=None):
    """"""
    if from_code == to_code:
        return amount

    if qs is None:
        qs = get_active_currencies_qs()

    from_, to = qs.get(code=from_code), qs.get(code=to_code)

    amount = D(amount) * (to.factor / from_.factor)
    return price_rounding(amount, decimals=decimals)
330836
public function convert(Money $money, Currency $counterCurrency, $roundingMode = Money::ROUND_HALF_UP)
    {
        $baseCurrency = $money->getCurrency();
        $ratio = $this->exchange->quote($baseCurrency, $counterCurrency)->getConversionRatio();

        $baseCurrencySubunit = $this->currencies->subunitFor($baseCurrency);
        $counterCurrencySubunit = $this->currencies->subunitFor($counterCurrency);
        $subunitDifference = $baseCurrencySubunit - $counterCurrencySubunit;

        $ratio = (string) Number::fromFloat($ratio)->base10($subunitDifference);

        $counterValue = $money->multiply($ratio, $roundingMode);

        return new Money($counterValue->getAmount(), $counterCurrency);
    }
169118
def normalise(self, to_currency):
        
        out = Money(currency=to_currency)
        for money in self._money_obs:
            out += converter.convert(money, to_currency)
        return Balance([out])
456552
function convert( $fromCurrency, $toCurrency, $value, $applyRounding = true )
    {
        if ( $fromCurrency == false || $toCurrency == false || $fromCurrency == $toCurrency || $value == 0 )
            return $value;

        $math = $this->mathHandler();

        $crossRate = $this->crossRate( $fromCurrency, $toCurrency );
        $convertedValue = $math->mul( $value, $crossRate );
        if ( $applyRounding )
        {
            switch ( $this->roundingType() )
            {
                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_ROUND':
                {
                    $convertedValue = $math->round( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_CEIL':
                {
                    $convertedValue = $math->ceil( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_FLOOR':
                {
                    $convertedValue = $math->floor( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_NONE':
                default:
                    break;
            }
        }

        return $convertedValue;
    }
1271608
def valueFromText( self, text ):
        
        value, currency = projex.money.fromString(text)
        
        return value
661859
def convert_currency(amount, from_currency, to_currency):
    '''
    

    '''
    try:
        rate = CurrencyRate.objects.get(
            from_currency__iso_code=from_currency,
            to_currency__iso_code=to_currency)
    except CurrencyRate.DoesNotExist:
        return _('n/a')
    try:
        history = rate.history.all()[0]
    except IndexError:
        return _('n/a')
    return amount * history.value
172421
def cache_rate(self, currency, date, rate):
        
        if not self.is_supported(defaults.INTERNAL_CURRENCY):
            logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
        else:
            cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date))