Java Currency Converter: Live Exchange Rates with BigDecimal

5 min read

Java Currency Converter: Live Exchange Rates with BigDecimal

A Java currency converter needs three things: a live exchange rate, exact decimal math, and a deliberate rounding step. Java gives you the last two out of the box with BigDecimal and RoundingMode. The first one is an HTTP call to a rate API.

This guide builds a small, dependency-light converter with Java 17's built-in HttpClient and Jackson for JSON. It covers parsing rates as BigDecimal from strings, converting, rounding to the right number of decimals per currency, and handling API errors. Every number in the examples is illustrative, not a current market rate.

Why double is the wrong type for exchange rates

double stores binary fractions, so most decimal values can't be represented exactly. The classic demonstration works with any rate:

double rate = 1.0842;
double amount = 125.50;
System.out.println(rate * amount); // may print a long tail like 136.06710000000001

One conversion with an error in the 14th digit looks harmless. But sum a few thousand line items, compare totals with ==, or reconcile against a bank statement, and the errors show up as one-cent differences that are painful to trace.

The fix is to keep rates and amounts as decimals from the moment they arrive. That means the API should not send them as JSON numbers either, because many JSON parsers turn numbers into double by default. GetRatesAPI returns rates and amounts as JSON strings, so you can hand them straight to new BigDecimal(String) with no lossy step in between.

Two BigDecimal rules to remember:

  • Always construct from a String, never from a double. new BigDecimal(0.1) captures the binary error; new BigDecimal("0.1") does not.
  • Compare with compareTo, not equals. new BigDecimal("1.10").equals(new BigDecimal("1.1")) is false because the scales differ.

Fetch a live rate with HttpClient

The current rate endpoint returns one pair per call. The response looks like this:

{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}

Besides the rate, you get as_of (when it was observed), status (fresh or stale) and type (direct or derived). Keep all of them. They matter later for auditing and for deciding whether to trust a value.

Here is a minimal client. The API key is read from an environment variable, and the authentication header is Authorization: ApiKey <key>.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class RatesClient {
    private static final String BASE_URL = "https://api.getratesapi.com";

    private final HttpClient http = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(5))
            .build();
    private final ObjectMapper mapper = new ObjectMapper();
    private final String apiKey = System.getenv("GETRATES_API_KEY");

    public record Rate(String base, String quote, BigDecimal rate,
                       String asOf, String status, String type) {}

    public static class RatesApiException extends RuntimeException {
        public final int httpStatus;
        public final String code;
        public final String requestId;

        public RatesApiException(int httpStatus, String code, String message, String requestId) {
            super(code + ": " + message);
            this.httpStatus = httpStatus;
            this.code = code;
            this.requestId = requestId;
        }
    }

    public Rate getRate(String base, String quote) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(
                        URI.create(BASE_URL + "/v1/rates/" + base + "/" + quote))
                .timeout(Duration.ofSeconds(10))
                .header("Authorization", "ApiKey " + apiKey)
                .GET()
                .build();

        HttpResponse<String> response =
                http.send(request, HttpResponse.BodyHandlers.ofString());
        JsonNode body = mapper.readTree(response.body());

        if (response.statusCode() != 200) {
            throw new RatesApiException(
                    response.statusCode(),
                    body.path("code").asText(),
                    body.path("message").asText(),
                    body.path("request_id").asText());
        }

        return new Rate(
                body.get("base").asText(),
                body.get("quote").asText(),
                new BigDecimal(body.get("rate").asText()),
                body.get("as_of").asText(),
                body.get("status").asText(),
                body.get("type").asText());
    }
}

Note asText() on the rate node: because the value is a JSON string, you get the exact digits the API sent. Validate currency codes before building the URL if they come from user input; the API answers an unknown symbol with invalid_asset_symbol, but there is no reason to spend a round trip on it.

Convert and round the result

With a BigDecimal rate, conversion is one multiplication. multiply is exact, so nothing is lost until you choose to round:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;

public static BigDecimal convert(BigDecimal amount, BigDecimal rate, String quoteCode) {
    BigDecimal exact = amount.multiply(rate);
    int digits = Currency.getInstance(quoteCode).getDefaultFractionDigits();
    return exact.setScale(digits, RoundingMode.HALF_EVEN);
}

// Example
RatesClient client = new RatesClient();
RatesClient.Rate r = client.getRate("EUR", "USD");
BigDecimal usd = convert(new BigDecimal("125.50"), r.rate(), "USD");
System.out.println(usd.toPlainString());

A few details that save debugging time:

  • Round once, at the end. Don't round the rate, and don't round intermediate results. The API does not round for you; it returns the full-precision value so you can apply your own policy.
  • Use the currency's own scale. Currency.getDefaultFractionDigits() returns 2 for USD, 0 for JPY and 3 for KWD. Hard-coding 2 breaks yen and dinar amounts.
  • Pick a rounding mode on purpose. HALF_EVEN (banker's rounding) and HALF_UP are both common. Your accounting rules or tax authority may dictate one. The reasoning is covered in currency conversion rounding without floating-point errors.
  • Print with toPlainString(). BigDecimal.toString() can produce scientific notation such as 1E+2, which you don't want in an invoice or a JSON payload.
  • Crypto codes aren't ISO currencies. Currency.getInstance("BTC") throws IllegalArgumentException. For crypto, define the display precision yourself, for example 8 decimals.

Let the API do the conversion

If you would rather not multiply yourself, the convert endpoint takes the amount and returns an exact converted_amount string:

curl "https://api.getratesapi.com/v1/convert?from=USD&to=EUR&amount=125.50" \
  -H "Authorization: ApiKey $GETRATES_API_KEY"

Both approaches cost one request unit. Fetching the rate and multiplying locally is better when you convert many amounts with the same rate, such as pricing a whole catalog or a list of invoice lines. Using /v1/convert is simpler for one-off conversions.

Inverting a rate

If you have EUR to USD and need USD to EUR, divide with an explicit precision, because BigDecimal.divide throws an ArithmeticException on non-terminating results:

import java.math.MathContext;

BigDecimal inverse = BigDecimal.ONE.divide(rate, MathContext.DECIMAL128);

In most cases it's cleaner to request the pair you need directly. Any pair works, including ones that no market quotes directly: the API derives them through USD, EUR or BTC and marks them "type": "derived". A derived rate's as_of is its oldest input, so the timestamp is never more optimistic than reality. See cross rates explained for the math behind that.

Handle errors and stale rates

Errors come back as JSON with code, message and request_id. Branch on code only, since message text can change. The error reference lists them all; the ones you will hit most in a Java service:

try {
    RatesClient.Rate r = client.getRate("USD", "EUR");
    // use r.rate()
} catch (RatesClient.RatesApiException e) {
    switch (e.code) {
        case "invalid_asset_symbol", "unsupported_pair" ->
            // Your input is wrong; don't retry.
            System.err.println("Bad pair, request_id=" + e.requestId);
        case "rate_limit_exceeded", "temporarily_unavailable" ->
            // Retry later with backoff.
            System.err.println("Retry later, request_id=" + e.requestId);
        case "quota_exceeded", "unauthorized" ->
            // Needs a human: upgrade the plan or fix the key.
            System.err.println("Config problem, request_id=" + e.requestId);
        default -> throw e;
    }
}

For rate_limit_exceeded the body includes retry_after_seconds, which is better than guessing a delay. Handling 429 errors and retries goes deeper on backoff.

Also check status. Stale rates are flagged, not withheld, so your code decides what to do with them. Crypto counts as stale after 1 minute and fiat after 5 minutes. A reasonable policy: show a stale rate with a visible "as of" time on a dashboard, but refuse to finalize an invoice or a checkout total on one.

Finally, store rate, as_of and type next to every converted amount you persist. When someone asks why an order was charged 136.07 USD, you can answer exactly.

Cache carefully

Calling the API for every page view wastes request units. A short in-memory cache keyed by pair, with a time-to-live shorter than the staleness window, is usually enough. Crypto refreshes every 10 seconds and fiat and metals every 60 seconds, so caching fiat for 30 to 60 seconds costs you almost no accuracy. The trade-offs are covered in how to cache exchange rates without showing stale prices.

Try it with a free key

You can run this converter today on the free plan, which needs no credit card: create an account, copy a key from the dashboard, export it as GETRATES_API_KEY, and test each endpoint in the built-in playground before wiring it into your code. If your volume grows, the pricing page lists the plans and limits.

All articles →
Java Currency Converter with BigDecimal and Live Rates — GetRatesAPI