PHP Currency Converter: Live Exchange Rates with BCMath, No Float Errors
5 min read
A reliable PHP currency converter needs three things: a live exchange rate, exact decimal math, and a deliberate rounding step. The first part is one HTTP call. The other two are where most PHP money code goes wrong, because PHP happily turns decimal numbers into binary floats without telling you.
This guide builds a small converter with plain cURL and the BCMath extension. Rates and amounts stay strings from the API response to the final rounded value. You can paste the code into a Laravel, Symfony or plain PHP project, since it has no dependencies beyond ext-curl, ext-json and ext-bcmath.
Why floats break a PHP currency converter
PHP's float is a 64-bit binary number. Many decimal values cannot be stored exactly in binary, so small errors creep in:
var_dump(0.1 + 0.2 == 0.3); // bool(false)
echo 0.1 + 0.2; // 0.3 (display is rounded)
printf("%.20f\n", 0.1 + 0.2); // 0.30000000000000004441
For a price of 19.99 multiplied by a rate, the error is tiny, but it shows up at the worst moment: a total that is one cent off, a refund that does not match the original charge, or a reconciliation report that never balances.
The usual trap is json_decode. If an API returns a rate as a JSON number, json_decode gives you a float immediately, before your code has a chance to be careful. GetRatesAPI returns rates and amounts as JSON strings, for example "rate":"1.0842", so json_decode hands you a string and nothing is lost. Keep it that way until the last step.
The rule: never cast a rate or an amount to float, and never use *, + or round() on money values. Use BCMath functions on strings instead. For a deeper look at the theory, see currency conversion rounding without floating-point errors.
Fetch a live exchange rate with cURL
The current rate endpoint returns one pair per call. Authentication is a single header, described in the authentication docs. Here is a minimal client that reads the key from an environment variable and turns API errors into exceptions:
<?php
declare(strict_types=1);
final class RatesApiException extends RuntimeException
{
public function __construct(
public readonly string $errorCode,
int $httpStatus,
public readonly ?string $requestId = null,
) {
parent::__construct("Rates API error {$errorCode} (HTTP {$httpStatus})", $httpStatus);
}
}
final class RatesClient
{
public function __construct(
private string $apiKey,
private string $baseUrl = 'https://api.getratesapi.com',
) {}
/** @return array<string, mixed> */
public function get(string $path, array $query = []): array
{
$url = $this->baseUrl . $path;
if ($query !== []) {
$url .= '?' . http_build_query($query);
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTPHEADER => [
'Authorization: ApiKey ' . $this->apiKey,
'Accept: application/json',
],
]);
$body = curl_exec($ch);
if ($body === false) {
$message = curl_error($ch);
curl_close($ch);
throw new RuntimeException("Network error: {$message}");
}
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400) {
throw new RatesApiException(
$data['code'] ?? 'unknown',
$status,
$data['request_id'] ?? null,
);
}
return $data;
}
public function rate(string $base, string $quote): array
{
return $this->get('/v1/rates/' . rawurlencode($base) . '/' . rawurlencode($quote));
}
}
$client = new RatesClient(getenv('GETRATESAPI_KEY'));
$rate = $client->rate('USD', 'EUR');
// e.g. {"base":"USD","quote":"EUR","rate":"0.9226","as_of":"...","status":"fresh","type":"direct"}
Three fields are worth reading, not just the rate itself:
as_ofis the time of the observation. Store it next to any amount you convert.statusisfreshorstale. Stale rates are flagged rather than withheld, so your code decides what to do.typeisdirectorderived. Pairs that no market quotes directly are derived through USD, EUR or BTC, and a derived rate'sas_ofis the oldest of its inputs.
Convert with BCMath and round on purpose
Once you have the rate string, conversion is a multiplication. BCMath works on numeric strings and never touches floats. It also truncates instead of rounding, so you need an explicit rounding helper.
<?php
declare(strict_types=1);
/** Round half up to $scale decimals, working on strings only. */
function roundHalfUp(string $value, int $scale): string
{
$offset = '0.' . str_repeat('0', $scale) . '5';
return str_starts_with($value, '-')
? bcsub($value, $offset, $scale)
: bcadd($value, $offset, $scale);
}
/** Decimal places per currency; extend as needed. */
const MINOR_UNITS = ['USD' => 2, 'EUR' => 2, 'GBP' => 2, 'JPY' => 0, 'KWD' => 3];
function convert(string $amount, string $rate, string $toCurrency): string
{
$exact = bcmul($amount, $rate, 20); // keep extra precision
$scale = MINOR_UNITS[$toCurrency] ?? 2; // round once, at the end
return roundHalfUp($exact, $scale);
}
echo convert('125.50', '0.9226', 'EUR'); // 115.79 (exact product: 115.7863)
echo convert('125.50', '149.8', 'JPY'); // 18800 (example rate)
The numbers above are examples, not current market rates. The important part is the order of operations: multiply with generous precision, then round once to the minor units of the target currency. Rounding the rate, or rounding in the middle of a chain of conversions, accumulates error.
Note that currencies differ: JPY has no minor unit, while KWD has three decimals. Do not hard-code two decimals everywhere. Which rounding mode you use (half up, banker's rounding) is a business or accounting rule, so pick one and apply it consistently.
Let the API do the conversion
If you prefer not to multiply yourself, the convert endpoint does exact decimal math server-side:
$result = $client->get('/v1/convert', [
'from' => 'USD',
'to' => 'EUR',
'amount' => '125.50',
]);
echo $result['converted_amount']; // exact, not rounded
converted_amount is a string and is not rounded. You still round it for display or invoicing, using the helper above. Both approaches cost 1 request unit per call, so choose based on whether you need the rate itself (to store, to reuse for a basket of line items) or just the final number.
Convert many prices with one request
A product catalog or dashboard often needs one base currency against several quotes. Instead of looping over single-pair calls, request up to 20 quotes in one call:
$data = $client->get('/v1/rates/USD', ['quote' => 'EUR,GBP,JPY']);
This counts as 1 request unit. Quotes the API does not support are listed in an unsupported field instead of failing the whole call, so check that field before assuming every currency came back. You can see all supported codes on the currencies page, or fetch them from the assets endpoints, which are free and not billed.
Handle errors and stale rates
Production code should decide in advance what happens when a rate is missing, late or rejected. Error responses are JSON with code, message and request_id. Match on code, never on the message text. See the error reference for the full list.
try {
$rate = $client->rate('USD', 'EUR');
} catch (RatesApiException $e) {
switch ($e->errorCode) {
case 'invalid_asset_symbol':
case 'unsupported_pair':
// Bad input: show a validation message, do not retry.
break;
case 'rate_limit_exceeded':
case 'temporarily_unavailable':
// Transient: retry with backoff, or use a cached rate.
break;
case 'quota_exceeded':
// Monthly units used up: alert, and fall back to cache.
break;
case 'unauthorized':
// Check the key in your environment configuration.
break;
default:
error_log("Rates error, request_id={$e->requestId}");
}
}
if ($rate['status'] === 'stale') {
// Decide: show with a warning, block checkout, or use a fallback.
}
Log the request_id with every failure; it makes support questions much faster to answer. For retry timing on 429 responses, which include retry_after_seconds, see how to handle API rate limits and retries.
Cache, but keep as_of
Fetching a rate on every page view wastes request units. Cache each pair in APCu, Redis or your framework's cache for a short time, and store the whole response, including as_of and status. Crypto prices refresh every 10 seconds and fiat and metals every 60 seconds, so a cache lifetime much longer than that only makes your data older, not cheaper to trust. The details are covered in how to cache exchange rates without showing stale prices.
Checklist for PHP money code
- Keep rates and amounts as strings from
json_decodeto the database (useDECIMAL, notFLOAT). - Use
bcmul,bcadd,bcsubandbcdivwith an explicit scale. Neverround()on money. - Round once, at the end, using the target currency's minor units.
- Store the rate,
as_of,statusandtypewith each converted amount, so you can explain it later. - Branch on error
code, and plan forstaledata.
Try it with a free key
GetRatesAPI covers about 170 world currencies, gold and silver, and thousands of crypto assets through one REST API. Sign up for a free plan (no credit card), create a key in the dashboard, and test your first request in the built-in playground. When your traffic grows, compare the options on the pricing page.