C# Currency Converter: Live Exchange Rates with System.Decimal

5 min read

C# Currency Converter: Live Exchange Rates with System.Decimal

A reliable C# currency converter comes down to three decisions: fetch the rate over HTTP, keep every money value in decimal (never double), and round exactly once at the end. Everything else is plumbing.

This guide builds that converter for modern .NET with HttpClient and System.Text.Json. It parses rates as exact decimals, rounds by currency, maps API errors to a typed exception, and checks whether a rate is fresh. The API calls use GetRatesAPI, but the structure works with any rate source that returns decimal strings.

Why decimal, and why the rate must arrive as a string

C# gives you three numeric types people reach for: double, float and decimal. The first two are binary floating point. They cannot represent values like 0.1 or 1.0842 exactly, and the error shows up when you multiply and round.

decimal is base-10 with 28-29 significant digits. A rate such as 1.0842 is stored exactly, and 125.50m * 1.0842m gives an exact product. That is the right tool for money.

There is a trap on the way in, though. If an API returns the rate as a JSON number, a default System.Text.Json model that declares it as double has already lost precision before your code runs. GetRatesAPI avoids this by returning rates and amounts as JSON strings, for example:

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

You declare Rate as string and parse it yourself with decimal.Parse. Two details matter:

  • Always pass CultureInfo.InvariantCulture. On a machine with a German or French culture, decimal.Parse("1.0842") can throw or misread the decimal point.
  • Do not round when parsing. Keep the full value and round only for display or the invoice line.

For the general theory behind this, see our article on currency conversion rounding without floating-point errors.

Step 1: A small typed client

Create the models first. The property names in the API are snake_case, so map them explicitly.

using System.Text.Json.Serialization;

public sealed record RateResponse(
    [property: JsonPropertyName("base")] string Base,
    [property: JsonPropertyName("quote")] string Quote,
    [property: JsonPropertyName("rate")] string Rate,
    [property: JsonPropertyName("as_of")] DateTimeOffset AsOf,
    [property: JsonPropertyName("status")] string Status,
    [property: JsonPropertyName("type")] string Type);

public sealed record ApiError(
    [property: JsonPropertyName("code")] string Code,
    [property: JsonPropertyName("message")] string? Message,
    [property: JsonPropertyName("request_id")] string? RequestId,
    [property: JsonPropertyName("retry_after_seconds")] int? RetryAfterSeconds);

public sealed class RatesApiException : Exception
{
    public string Code { get; }
    public int HttpStatus { get; }
    public int? RetryAfterSeconds { get; }
    public string? RequestId { get; }

    public RatesApiException(string code, int httpStatus, int? retryAfter, string? requestId)
        : base($"Rates API error: {code} (HTTP {httpStatus})")
    {
        Code = code;
        HttpStatus = httpStatus;
        RetryAfterSeconds = retryAfter;
        RequestId = requestId;
    }
}

Now the client. It takes an HttpClient so you can configure it once and reuse it. Creating a new HttpClient per call is a classic source of socket exhaustion.

using System.Globalization;
using System.Net.Http.Headers;
using System.Text.Json;

public sealed class RatesClient
{
    private readonly HttpClient _http;

    public RatesClient(HttpClient http) => _http = http;

    public static HttpClient CreateHttpClient(string apiKey)
    {
        var http = new HttpClient
        {
            BaseAddress = new Uri("https://api.getratesapi.com"),
            Timeout = TimeSpan.FromSeconds(10)
        };
        http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("ApiKey", apiKey);
        return http;
    }

    public Task<RateResponse> GetRateAsync(
        string baseCode, string quoteCode, CancellationToken ct = default) =>
        GetAsync<RateResponse>(
            $"/v1/rates/{Uri.EscapeDataString(baseCode)}/{Uri.EscapeDataString(quoteCode)}", ct);

    public async Task<string> ConvertAsync(
        string from, string to, decimal amount, CancellationToken ct = default)
    {
        var amountText = amount.ToString(CultureInfo.InvariantCulture);
        var path = $"/v1/convert?from={Uri.EscapeDataString(from)}" +
                   $"&to={Uri.EscapeDataString(to)}&amount={amountText}";
        var json = await GetAsync<JsonElement>(path, ct);
        return json.GetProperty("converted_amount").GetString()
               ?? throw new InvalidOperationException("Missing converted_amount");
    }

    private async Task<T> GetAsync<T>(string path, CancellationToken ct)
    {
        using var response = await _http.GetAsync(path, ct);
        var body = await response.Content.ReadAsStringAsync(ct);

        if (!response.IsSuccessStatusCode)
        {
            ApiError? error = null;
            try { error = JsonSerializer.Deserialize<ApiError>(body); }
            catch (JsonException) { /* non-JSON error body */ }

            throw new RatesApiException(
                error?.Code ?? "unknown_error",
                (int)response.StatusCode,
                error?.RetryAfterSeconds,
                error?.RequestId);
        }

        return JsonSerializer.Deserialize<T>(body)
               ?? throw new InvalidOperationException("Empty response body");
    }
}

The API key comes from an environment variable, never from source code. Authentication is a single header, Authorization: ApiKey <key>; see the authentication docs for how keys are created and rotated.

Step 2: Convert and round once

You have two options for converting, and both are exact.

Option A: let the API convert. GET /v1/convert returns converted_amount as a string. You parse it and round for display.

Option B: fetch the rate and multiply locally. This is useful when you convert many amounts with the same rate, such as every line on an invoice, because you pay for one request unit instead of one per line.

using System.Globalization;

public static class Money
{
    // Minor-unit digits per currency. Extend this from your own currency table.
    private static readonly Dictionary<string, int> Decimals = new()
    {
        ["USD"] = 2, ["EUR"] = 2, ["GBP"] = 2,
        ["JPY"] = 0, ["KWD"] = 3
    };

    public static int DecimalsFor(string currency) =>
        Decimals.TryGetValue(currency, out var d) ? d : 2;

    public static decimal ParseExact(string value) =>
        decimal.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);

    public static decimal Convert(decimal amount, string rate, string quoteCurrency)
    {
        var exact = amount * ParseExact(rate);
        return Math.Round(
            exact, DecimalsFor(quoteCurrency), MidpointRounding.AwayFromZero);
    }
}

Note the two rounding choices. Math.Round in .NET defaults to banker's rounding (MidpointRounding.ToEven), which surprises many people who expect 2.345 to become 2.35. Pick the mode your accounting rules require and state it explicitly, as above. Also note that currencies do not all use two decimals: JPY has none and KWD has three, so the number of digits must depend on the currency.

Putting it together:

var apiKey = Environment.GetEnvironmentVariable("GETRATESAPI_KEY")
    ?? throw new InvalidOperationException("Set GETRATESAPI_KEY");

var client = new RatesClient(RatesClient.CreateHttpClient(apiKey));

var rate = await client.GetRateAsync("USD", "EUR");
var total = Money.Convert(125.50m, rate.Rate, "EUR");

Console.WriteLine($"125.50 USD = {total} EUR (rate {rate.Rate}, {rate.Type}, as of {rate.AsOf:u})");

The numbers you see depend on the market when you run it. Treat any value in this article as an example, not a quote.

Step 3: Check freshness and handle errors

Every rate carries as_of and a status of fresh or stale. Crypto is flagged stale after 1 minute, fiat after 5 minutes. A stale rate is still returned, so deciding what to do about it is your job.

if (rate.Status == "stale")
{
    // Log it, show "rate may be outdated", or block checkout for payment flows.
    logger.LogWarning("Stale rate {Base}/{Quote} as of {AsOf}", rate.Base, rate.Quote, rate.AsOf);
}

For display-only prices, a warning is usually enough. For something that locks in money, such as an invoice or a quote, consider refusing a stale rate and retrying.

The type field tells you whether the rate is direct or derived through USD, EUR or BTC. For a derived rate, as_of is the oldest input, so the freshness check already accounts for the weakest link. If you want to see how derived rates work, read cross rates explained.

For errors, match on code and ignore the human-readable message:

try
{
    var r = await client.GetRateAsync("USD", "EUR");
}
catch (RatesApiException ex) when (ex.Code == "rate_limit_exceeded")
{
    await Task.Delay(TimeSpan.FromSeconds(ex.RetryAfterSeconds ?? 1));
    // retry once, with a cap on attempts
}
catch (RatesApiException ex) when (ex.Code is "invalid_asset_symbol" or "unsupported_pair")
{
    // Caller or data problem: do not retry. Show a clear message.
}
catch (RatesApiException ex) when (ex.Code == "temporarily_unavailable")
{
    // Retry with backoff, or fall back to the last known rate (clearly labeled).
}

Retrying a 400 or 404 never helps. Retrying 429 and 503 does, with limits. The full list of codes and sensible reactions is in our error handling guide and the errors reference.

Common C# pitfalls

MistakeWhat goes wrongFix
double for amounts or ratesBinary rounding errors accumulateUse decimal everywhere
decimal.Parse without a cultureWrong or failing parse on non-English systemsPass CultureInfo.InvariantCulture
Default Math.RoundBanker's rounding gives unexpected centsSet MidpointRounding explicitly
Rounding the rateCompounding error across linesRound only the final money amount
New HttpClient per requestSocket exhaustion, slow callsReuse one instance or use IHttpClientFactory
Fixed two decimalsWrong amounts for JPY or KWDLook up digits per currency

Using it in ASP.NET Core

In a web app, register the client through IHttpClientFactory so connection handling is managed for you:

builder.Services.AddHttpClient<RatesClient>(http =>
{
    http.BaseAddress = new Uri("https://api.getratesapi.com");
    http.Timeout = TimeSpan.FromSeconds(10);
    http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "ApiKey", builder.Configuration["GetRatesApi:Key"]);
});

Keep the key in user secrets locally and in your host's secret store in production. If the same pair is requested on every page view, add a short in-memory cache keyed by pair, and let the TTL follow the rate's freshness. We cover that in how to cache exchange rates without showing stale prices. When you need several quotes against one base, a single call returns up to 20 of them for one request unit; see getting multiple exchange rates in one call.

Try it with your own key

The free plan needs no credit card, so you can run the code above today. Sign up for a free key, try the endpoints in the dashboard playground, and read the current rate reference for the full response format. When you outgrow the free quota, compare options on the pricing page.

All articles →
C# Currency Converter: Live Rates with decimal — GetRatesAPI