Ruby Currency Converter: Live Exchange Rates with BigDecimal

4 min read

Ruby Currency Converter: Live Exchange Rates with BigDecimal

A reliable Ruby currency converter needs three things: a live exchange rate, arithmetic that does not use Float, and a deliberate rounding step at the end. Ruby makes the second part easy with BigDecimal, which ships with the language. The first part is one HTTP call.

This guide builds a small converter with nothing but the standard library (net/http, json, bigdecimal). It works in a script, a Sidekiq job or a Rails service object. We will fetch a rate, convert an amount exactly, round for display, and handle errors and stale data.

Why Float is the wrong type for a Ruby currency converter

Ruby floats are binary approximations. You see it in the first line of irb:

0.1 + 0.2          # => 0.30000000000000004
BigDecimal("0.1") + BigDecimal("0.2") == BigDecimal("0.3")  # => true

One cent of drift is invisible in a demo and very visible when you sum 40,000 invoice lines and the total no longer matches the ledger. Here is how Ruby's numeric types compare for money:

TypeExact for decimals?Good for money?
FloatNoNo
RationalYes, but values like 1/3 grow awkwardRarely
BigDecimalYes, for decimal inputYes
Integer minor units (cents)YesYes, for storing amounts

Two habits keep you safe. Always build a BigDecimal from a string, never from a float. In fact BigDecimal(0.1) raises an ArgumentError unless you pass a precision, which is Ruby protecting you from yourself. And never let a rate pass through to_f.

This is why GetRatesAPI returns rates and amounts as JSON strings. "1.0842" goes straight into BigDecimal("1.0842") with no lossy step in between. For the general reasoning behind rounding choices, see currency conversion rounding without floating-point errors.

Fetch a live rate with Net::HTTP

Authentication is a single header, Authorization: ApiKey <key>. Keep the key in an environment variable, never in source. See the authentication docs for creating and rotating keys.

require "net/http"
require "json"
require "uri"
require "bigdecimal"

class RatesError < StandardError
  attr_reader :code, :request_id, :retry_after

  def initialize(code, message, request_id: nil, retry_after: nil)
    super("#{code}: #{message}")
    @code = code
    @request_id = request_id
    @retry_after = retry_after
  end
end

class RatesClient
  BASE_URL = "https://api.getratesapi.com".freeze

  def initialize(api_key: ENV.fetch("GETRATES_API_KEY"))
    @api_key = api_key
  end

  # Returns the parsed JSON for one rate, e.g.
  # {"base"=>"EUR","quote"=>"USD","rate"=>"1.0842",
  #  "as_of"=>"2026-01-02T10:00:00Z","status"=>"fresh","type"=>"direct"}
  def rate(base, quote)
    get("/v1/rates/#{base}/#{quote}")
  end

  def convert(from, to, amount)
    get("/v1/convert", from: from, to: to, amount: amount)
  end

  private

  def get(path, params = {})
    uri = URI("#{BASE_URL}#{path}")
    uri.query = URI.encode_www_form(params) unless params.empty?

    request = Net::HTTP::Get.new(uri)
    request["Authorization"] = "ApiKey #{@api_key}"
    request["Accept"] = "application/json"

    response = Net::HTTP.start(uri.host, uri.port,
                               use_ssl: true,
                               open_timeout: 3,
                               read_timeout: 5) do |http|
      http.request(request)
    end

    body = JSON.parse(response.body)
    return body if response.is_a?(Net::HTTPSuccess)

    raise RatesError.new(body["code"], body["message"],
                         request_id: body["request_id"],
                         retry_after: body["retry_after_seconds"])
  end
end

Note the explicit timeouts. Ruby's defaults are generous, and a checkout page should not hang for a minute because of a slow upstream call. The current rate endpoint docs describe every field in the response.

Convert and round with BigDecimal

Once you have the rate, the conversion is a multiplication. Rounding happens once, at the very end, with a mode you chose on purpose.

client = RatesClient.new

data = client.rate("USD", "EUR")
rate = BigDecimal(data["rate"])          # string in, exact decimal out
amount = BigDecimal("125.50")

exact = amount * rate
display = exact.round(2, :half_up)

puts exact.to_s("F")    # e.g. 115.64825 when the rate is 0.9215
puts display.to_s("F")  # 115.65

The rate 0.9215 is only an example. With it, 125.50 * 0.9215 is exactly 115.64825, which rounds half-up to 115.65. With floats you can land on the wrong side of a half-cent tie; with BigDecimal you cannot.

Currencies with different minor units

Not every currency has two decimals. JPY has none, and some currencies have three. Keep a small lookup, or use a money library, rather than hardcoding 2:

MINOR_UNITS = { "USD" => 2, "EUR" => 2, "JPY" => 0, "KWD" => 3 }.freeze

def round_money(value, currency)
  value.round(MINOR_UNITS.fetch(currency, 2), :half_up)
end

Let the API do the arithmetic

If you would rather not multiply yourself, /v1/convert returns an exact converted_amount as a string. It is not rounded, so you still round for display or invoicing.

result = client.convert("USD", "EUR", "125.50")
converted = BigDecimal(result["converted_amount"])
puts round_money(converted, "EUR").to_s("F")

Pass the amount as a string. If the amount is malformed, the API answers with invalid_amount, and malformed requests are not billed. Details are in the convert endpoint docs.

Check freshness before you trust a rate

Every rate carries as_of and status. Crypto is flagged stale after one minute and fiat after five. Stale rates are flagged, not withheld, so the decision about what to do belongs to your code.

def usable_rate!(data, allow_stale: false)
  if data["status"] == "stale" && !allow_stale
    raise "Rate #{data['base']}/#{data['quote']} is stale (as_of #{data['as_of']})"
  end
  BigDecimal(data["rate"])
end

A sensible policy depends on the screen. A product listing can show a slightly old price with a note. A payment confirmation should probably refuse a stale rate, or fall back to a rate you locked earlier. Also check type: a derived rate was computed through USD, EUR or BTC, and its as_of is the oldest of its inputs. That is normal for pairs without a direct market, and it means any pair works. For the background, read cross rates explained.

Handle errors and retries

Errors come back as JSON with code, message and request_id. Branch on code only, because message text can change. A compact retry wrapper:

def with_retries(max_attempts: 3)
  attempts = 0
  begin
    attempts += 1
    yield
  rescue RatesError => e
    case e.code
    when "rate_limit_exceeded"
      raise if attempts >= max_attempts
      sleep(e.retry_after || 1)
      retry
    when "temporarily_unavailable"
      raise if attempts >= max_attempts
      sleep(2**attempts * 0.25)
      retry
    else
      # invalid_asset_symbol, invalid_amount, unauthorized,
      # unsupported_pair, quota_exceeded: retrying will not help
      raise
    end
  end
end

data = with_retries { client.rate("GBP", "JPY") }

Retry rate_limit_exceeded after the wait the API gives you, and temporarily_unavailable with a short backoff. Do not retry the 400 and 404 codes; fix the request instead. Log the request_id with every failure so it can be traced later. The full list is in the error reference, and our error handling guide walks through each code.

Rails notes

  • Store money as integer minor units or as decimal columns with explicit precision and scale, never float.
  • Save the rate, its as_of and the quote currency next to every converted amount, so the number can be explained later.
  • Cache rates for a short time to stay inside your quota; the caching guide covers safe TTLs.
  • Wrap the client in a service object so tests can stub it with fixed string rates.

Try it yourself

You now have a converter that never touches Float, rounds once and on purpose, and treats stale data and errors as normal cases. To run it, sign up for a free GetRatesAPI key, no credit card needed, and try the calls in the dashboard playground first. The same endpoints cover about 170 fiat currencies, gold, silver and thousands of crypto assets, so the code above works unchanged for BTC to EUR or XAU to USD. See pricing for plan limits.

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