Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

9.3 KB
Raw Blame
---
title: "Monetary amounts in the Admin API: prices, costs, formats"
sidebarTitle: "Monetary Amounts"
description: "How the Admin API represents money as decimal strings, why JSON numbers are avoided, and how to send prices, costs, and amounts safely in requests."
---

All monetary values in the Admin API are **canonical decimal strings** (period decimal, no thousands grouping), both in responses and in request bodies. Responses write each amount with exactly its currency's decimal places — `"29.99"` in USD, `"1.500"` in Kuwaiti dinar, `"1000"` in yen — and unit prices (`price`, `amount` on a price, `compare_at_amount`, `cost_price`, `unit_cost`) with up to four (`"0.0125"`). A currency's decimal places are its `decimal_places`, from ISO 4217. Strings preserve decimal precision and avoid the floating-point rounding issues common with JSON numbers — critical when an admin is setting prices and costs. The format is the same regardless of locale; localized formatting is a presentation concern handled by the client (see [Canonical format](#canonical-format-not-localized)).

## Reading

Every monetary field is returned as a decimal string, with its currency on the record or on the record it belongs to (an order's payments and fulfillments are in the order's currency):

```json
{
  "amount": "29.99",
  "compare_at_amount": "39.99",
  "currency": "USD"
}
```

The Admin and Seller APIs return amounts only, with no `display_*` formatted copies: format them for the person reading them, in their own language. Format and calculate with the SDK's [money helpers](#money-helpers); without the SDK, pass the string to `Intl.NumberFormat`, which reads a numeric string exactly, and calculate with a decimal library rather than `parseFloat`. The [Store API](/api-reference/store-api/monetary-amounts) and webhook payloads still carry `display_*` fields, deprecated and removed in 6.1; email templates format amounts with the `money` filter.

## Money helpers

`@spree/admin-sdk` and `@spree/seller-sdk` export helpers that work on the decimal strings directly. None of them turns an amount into a JavaScript number, so a sum or a comparison is exact.

```typescript
import {
  compareMoney, decimalPlaces, formatMoney, isDecimalString, isZeroMoney,
  multiplyMoney, negateMoney, subtractMoney, sumMoney,
} from '@spree/admin-sdk'
```

### Displaying

| Helper | What it does | Example |
| --- | --- | --- |
| `formatMoney(amount, currency, locale?, { unitPrice? })` | Formats an amount in a currency and language, with the currency's own decimal places. Pass `{ unitPrice: true }` for a unit price, which keeps up to four decimals. A missing or malformed amount gives an empty string. | `formatMoney('1234.5', 'EUR', 'de')` → `"1.234,50 €"`<br/>`formatMoney('1000', 'JPY', 'en')` → `"¥1,000"`<br/>`formatMoney('0.0125', 'USD', 'en', { unitPrice: true })` → `"$0.0125"` |
| `decimalPlaces(currency)` | The number of decimals a currency's amounts are written with, from ISO 4217. An unknown code gives `2`. | `decimalPlaces('USD')` → `2`<br/>`decimalPlaces('JPY')` → `0`<br/>`decimalPlaces('KWD')` → `3` |

### Calculating

Pass a currency to write the result with that currency's decimal places. Without one, the result keeps only the decimals it needs.

| Helper | What it does | Example |
| --- | --- | --- |
| `sumMoney(amounts, currency?)` | Adds amounts. Blank values (`null`, `undefined`, `""`) count as zero. | `sumMoney(['19.99', '10.01'], 'USD')` → `"30.00"`<br/>`sumMoney(['19.99', '10.01'])` → `"30"`<br/>`sumMoney(['0.1', '0.2'])` → `"0.3"` |
| `subtractMoney(a, b, currency?)` | `a` minus `b`. | `subtractMoney('100.00', '29.99', 'USD')` → `"70.01"` |
| `multiplyMoney(amount, quantity, currency?)` | An amount times a whole quantity, such as a unit price times the units. A quantity that is not a whole number throws. | `multiplyMoney('19.99', 3, 'USD')` → `"59.97"` |
| `negateMoney(amount)` | The amount with its sign flipped. | `negateMoney('5.00')` → `"-5.00"` |

### Comparing and checking

| Helper | What it does | Example |
| --- | --- | --- |
| `compareMoney(a, b)` | `1` when `a` is larger, `-1` when it is smaller, `0` when they are equal, whatever their decimal places. | `compareMoney('10.00', '9.99')` → `1`<br/>`compareMoney('10', '10.00')` → `0` |
| `isZeroMoney(amount)` | Whether an amount is zero. Blank counts as zero. | `isZeroMoney('0.00')` → `true`<br/>`isZeroMoney(null)` → `true`<br/>`isZeroMoney('0.01')` → `false` |
| `isDecimalString(value)` | Whether a value is a canonical decimal string. | `isDecimalString('19.99')` → `true`<br/>`isDecimalString('1,99')` → `false`<br/>`isDecimalString(19.99)` → `false` |

The calculating and comparing helpers throw on a value that is not a canonical decimal string, such as `"1,99"` or `"1e3"`, rather than guess what it means. Check input you did not get from the API with `isDecimalString` first.

## Writing

Send amounts back as strings too, so a value reads and writes in the same type:

<CodeGroup>

```typescript Admin SDK
await client.products.create({
  name: 'Classic Tee',
  prices: [{ currency: 'USD', amount: '29.99', compare_at_amount: '39.99' }],
})
```

```bash CLI
spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99","compare_at_amount":"39.99"}]}'
```

</CodeGroup>

Only strings are accepted. A JSON number (`"amount": 29.99`), a localized or grouped string (`"1.234,56"`, `"1,234.56"`), or more decimals than the field holds (`"19.999"` in USD, `"100.5"` in yen; unit prices allow four) is refused with `422` and the error code `invalid_money_format`, naming the field:

```json
{
  "error": {
    "code": "invalid_money_format",
    "message": "amount must be a decimal string like \"19.99\"",
    "details": { "amount": ["must be a decimal string like \"19.99\""] }
  }
}
```

A `null` clears the value.

### Canonical format — not localized

Amounts are **canonical**: a period decimal separator and no thousands grouping (`"1234.56"`), independent of any locale. The Admin API does **not** parse locale-specific formats — do not send `"1.234,56"` or `"1,234.56"`.

If you are taking input from a merchant in a localized format, normalize it to canonical form **before** sending. The Spree dashboard does this in the browser, in the number format of the person using it: an admin who writes German types `1.234,56`, in any currency, and `1234.56` goes on the wire. This matches how other commerce APIs handle money (canonical decimal or minor-unit integers; localization is a presentation concern).

## Affected types

This convention applies to all monetary fields across all resources, including back-office-only fields the Store API never exposes:

| Resource | Monetary Fields |
|----------|----------------|
| **Product / Variant** | `price`, `compare_at_amount`, `cost_price` |
| **Price** | `amount`, `compare_at_amount` |
| **Order** | `total`, `item_total`, `ship_total`, `tax_total`, `adjustment_total`, `promo_total`, `included_tax_total`, `additional_tax_total` |
| **Line Item** | `price`, `total`, `adjustment_total`, `promo_total`, `pre_tax_amount`, `discounted_amount`, `compare_at_amount` |
| **Payment** | `amount` |
| **Refund** | `amount` |
| **Shipment** | `cost` |
| **Gift Card** | `amount`, `amount_used`, `amount_authorized`, `amount_remaining` |
| **Store Credit** | `amount`, `amount_used`, `amount_remaining` |

### Amounts inside `preferences`

Calculators and rules carry their amounts inside a `preferences` object rather than as top-level fields. Each type lists its preferences with their types in `preference_schema` (from its `…/types` endpoint), and a preference of type `money` follows the same convention as every other amount: a decimal string, read back with the decimals of the record's `currency` preference. On write, a money preference that is not a decimal string, or has more decimals than its currency, is refused with `422` and `invalid_preferences`, naming the field (`/calculator/preferences/amount`). The money preferences Spree ships:

| Resource | Money keys in `preferences` |
|----------|------------------------------|
| **Calculator** `flat_rate`, `per_item`, `digital_delivery` | `amount` |
| **Calculator** `flexi_rate` | `first_item`, `additional_item` |
| **Calculator** `price_sack` | `minimal_amount`, `normal_amount`, `discount_amount` |
| **Calculator** `tiered_flat_rate` | `base_amount`, and the values of `tiers` |
| **Calculator** `flat_rate` (shipping) | `amount`, `minimum_item_total`, `maximum_item_total` |
| **Promotion Rule** `item_total` | `amount_min`, `amount_max` |

Read an extension's money preferences from `preference_schema` rather than from this table. Percentage keys (`percent`, `flat_percent`, `base_percent`) are rates: decimal strings too (`"10"`), with no fixed number of decimals. Weights (`minimum_weight`, `maximum_weight`) and quantities (`max_items`, `min_quantity`) are not money and stay numbers. Promotion actions (`create_adjustment`, `create_item_adjustments`) hold their money inside a nested `calculator.preferences`, per the calculator rows above.

## Rates and percentages

Rates and percentages are decimal strings without trailing zeros, on read and write. A field ending in `_percent` or `_percentage` holds 0–100 (`"23"`); a field named `rate` or ending in `_rate` holds a fraction (`"0.23"`). A tax rate has both: `rate` and `rate_percent`, and accepts either on write.