Go Currency Converter: Live Exchange Rates with big.Rat and No Float Errors
5 min read
A good Go currency converter does three things: it fetches a live rate over HTTP, keeps that rate as an exact decimal instead of a float64, and rounds only once, at the very end, to the currency's minor unit. Go's standard library has no decimal type, but math/big is enough to do all of this correctly.
This guide builds a small, dependency-free converter in Go. You will get a typed API client with timeouts, exact multiplication with big.Rat, half-up rounding that respects currencies like JPY and KWD, and error handling that matches on stable error codes. The examples use the GetRatesAPI REST API, but the money-handling parts apply to any rate source.
Why float64 is the wrong type for a currency converter
Go will happily decode a JSON number into a float64, and that is where the trouble starts. Binary floating point cannot represent most decimal fractions exactly. 0.1 + 0.2 is not 0.3, and the same drift shows up when you multiply a price by a rate and sum the results over thousands of invoice lines.
The errors are tiny, but money has to reconcile to the cent. A total that is off by one minor unit breaks reports, fails audits and confuses customers. For the wider picture, see Currency Conversion Rounding: How to Convert Money Without Floating-Point Errors.
The fix has two halves:
- Receive rates as strings. GetRatesAPI returns rates and amounts as JSON strings, such as
"rate":"1.0842", so nothing is lost before your code sees it. - Compute with an exact type.
big.Ratstores a number as a fraction of two big integers. Parsing"1.0842"gives exactly 10842/10000, and multiplication stays exact.
A typed client for the rates endpoint
The current rate endpoint is GET /v1/rates/{base}/{quote}. A response looks like this:
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
Declare Rate as a string in your struct, not a float. Authentication is a single header, Authorization: ApiKey <key>, and the key should come from an environment variable, never from source code. See the authentication docs for key management.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
)
type Rate struct {
Base string `json:"base"`
Quote string `json:"quote"`
Rate string `json:"rate"` // exact decimal string, never float64
AsOf time.Time `json:"as_of"`
Status string `json:"status"` // "fresh" or "stale"
Type string `json:"type"` // "direct" or "derived"
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
RetryAfterSeconds int `json:"retry_after_seconds"`
HTTPStatus int `json:"-"`
}
func (e *APIError) Error() string {
return fmt.Sprintf("%s (HTTP %d, request %s)", e.Code, e.HTTPStatus, e.RequestID)
}
type Client struct {
APIKey string
BaseURL string
HTTP *http.Client
}
func NewClient(apiKey string) *Client {
return &Client{
APIKey: apiKey,
BaseURL: "https://api.getratesapi.com",
HTTP: &http.Client{Timeout: 5 * time.Second},
}
}
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
u := c.BaseURL + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "ApiKey "+c.APIKey)
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
apiErr := &APIError{HTTPStatus: resp.StatusCode, Code: "unknown"}
_ = json.NewDecoder(resp.Body).Decode(apiErr)
apiErr.HTTPStatus = resp.StatusCode
return apiErr
}
return json.NewDecoder(resp.Body).Decode(out)
}
func (c *Client) Rate(ctx context.Context, base, quote string) (*Rate, error) {
var r Rate
path := "/v1/rates/" + url.PathEscape(base) + "/" + url.PathEscape(quote)
if err := c.get(ctx, path, nil, &r); err != nil {
return nil, err
}
return &r, nil
}
Two details matter here. The http.Client has an explicit timeout, because Go's default client has none and a slow upstream would otherwise hang your checkout. And the context lets callers cancel the request when the user's own request goes away.
Exact conversion and rounding with math/big
Now the money math. The function below multiplies an amount string by a rate string as exact fractions, then rounds half up to the currency's minor unit using only integer arithmetic.
package main
import (
"fmt"
"math/big"
)
// Minor-unit exponents. Extend this from your own currency table.
var minorUnits = map[string]int{
"USD": 2, "EUR": 2, "GBP": 2,
"JPY": 0, "KWD": 3,
}
func ConvertAmount(amount, rate string, places int) (string, error) {
a, ok := new(big.Rat).SetString(amount)
if !ok || a.Sign() < 0 {
return "", fmt.Errorf("invalid amount %q", amount)
}
r, ok := new(big.Rat).SetString(rate)
if !ok || r.Sign() <= 0 {
return "", fmt.Errorf("invalid rate %q", rate)
}
product := new(big.Rat).Mul(a, r)
// Shift by 10^places so the minor unit becomes the integer part.
scale := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(places)), nil)
scaled := new(big.Rat).Mul(product, new(big.Rat).SetInt(scale))
// Round half up: floor((2n + d) / 2d) for non-negative n/d.
n, d := scaled.Num(), scaled.Denom()
num := new(big.Int).Mul(n, big.NewInt(2))
num.Add(num, d)
den := new(big.Int).Mul(d, big.NewInt(2))
q := new(big.Int).Div(num, den)
return formatMinor(q, places), nil
}
func formatMinor(q *big.Int, places int) string {
s := q.String()
if places == 0 {
return s
}
for len(s) <= places {
s = "0" + s
}
return s[:len(s)-places] + "." + s[len(s)-places:]
}
With an example rate of 0.9223 (an illustration, not a current quote), converting 125.50 USD gives an exact product of 115.74865, which rounds to 115.75 EUR. In JPY with places set to 0 you get a whole number, and in KWD you get three decimals. Looking up the exponent per currency is the part people forget; hardcoding two decimals breaks Japanese yen and Kuwaiti dinar prices.
Wiring it together:
func main() {
client := NewClient(os.Getenv("GETRATESAPI_KEY"))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
rate, err := client.Rate(ctx, "USD", "EUR")
if err != nil {
fmt.Fprintln(os.Stderr, "rate lookup failed:", err)
os.Exit(1)
}
out, err := ConvertAmount("125.50", rate.Rate, minorUnits[rate.Quote])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("125.50 USD = %s EUR (as of %s, %s, %s)\n",
out, rate.AsOf.Format(time.RFC3339), rate.Status, rate.Type)
}
Note that GetRatesAPI itself never rounds. Rates come back at full precision, and rounding is your decision, made once, at the edge where you display or invoice.
Or let the API do the multiplication
If you only need a one-off result, the convert endpoint does the exact math server-side: GET /v1/convert?from=USD&to=EUR&amount=125.50 returns a converted_amount string, also unrounded. Decode it into a string field and round it with the same helper. Use the rate endpoint when you need to store the rate itself, for example on an invoice.
Handle status, errors and rate limits
A converter that works on the happy path is half done. Three things deserve code.
Check status. Every rate carries "status": "fresh" or "stale". Stale rates are flagged, not withheld, so the decision is yours. A product page might tolerate a stale rate; a payment confirmation might not. Also keep as_of and type next to any amount you persist. A derived rate, computed through USD, EUR or BTC when no market quotes the pair, reports the as_of of its oldest input. Background on that in Cross Rates Explained.
Match on code, never on message text. The error reference lists the stable codes:
| Code | HTTP | What to do |
|---|---|---|
invalid_asset_symbol | 400 | Fix the currency code; do not retry |
invalid_amount | 400 | Fix the amount; do not retry |
unauthorized | 401 | Check the key and the header format |
unsupported_pair | 404 | Show a "not available" message |
rate_limit_exceeded | 429 | Wait retry_after_seconds, then retry |
quota_exceeded | 429 | Alert; retrying will not help until the period resets |
temporarily_unavailable | 503 | Retry with backoff |
Retry only what is retryable. A small helper keeps that logic in one place:
func (c *Client) RateWithRetry(ctx context.Context, base, quote string) (*Rate, error) {
var lastErr error
for attempt := 0; attempt < 3; attempt++ {
r, err := c.Rate(ctx, base, quote)
if err == nil {
return r, nil
}
lastErr = err
apiErr, ok := err.(*APIError)
if !ok {
return nil, err // network error: let the caller decide
}
wait := time.Duration(1<<attempt) * 500 * time.Millisecond
switch apiErr.Code {
case "rate_limit_exceeded":
if apiErr.RetryAfterSeconds > 0 {
wait = time.Duration(apiErr.RetryAfterSeconds) * time.Second
}
case "temporarily_unavailable":
// use the backoff above
default:
return nil, err
}
select {
case <-time.After(wait):
case <-ctx.Done():
return nil, ctx.Err()
}
}
return nil, lastErr
}
Rate-limited and malformed requests are not billed, but retries in a tight loop will still keep you limited. More on this in Exchange Rate API Rate Limits, and you can check your remaining quota with GET /v1/account/usage (usage and quotas).
Reduce calls with batching and caching
Go services tend to be concurrent, so it is easy to fire hundreds of identical rate lookups. Two habits help:
- Batch quotes.
GET /v1/rates/USD?quote=EUR,GBP,JPYreturns up to 20 quotes against one base for a single request unit. Unsupported quotes are listed in anunsupportedfield instead of failing the whole call. - Cache briefly. Fiat and metal rates refresh every 60 seconds and crypto every 10 seconds, so caching longer than that gains little. A short in-memory cache with
sync.RWMutexorsingleflightto collapse concurrent misses is usually enough. See How to Cache Exchange Rates Without Showing Stale Prices for expiry rules.
The currency catalog (/v1/assets, /v1/assets/fiat, /v1/assets/crypto) is free, so validating user-supplied codes against it at startup costs nothing. The full list is also on the currencies page.
Try it with a free key
Create a free account at app.getratesapi.com/signup, no credit card needed, copy a key into GETRATESAPI_KEY, and run the program above. The dashboard playground lets you try each endpoint before writing code, and the REST documentation covers every parameter. When you outgrow the free quota, compare plans on the pricing page.