How do I compare two money amounts and find the cheaper price in EK9?
← Operators and Expressions · Ref: Q1189
EK9 Money uses the same comparison and coalescing operators as every other type. Literals use amount#CURRENCY format.
MONEY LITERALS
priceA <- 29.99#USD priceB <- 45.50#USD
COMPARISON
if priceA < priceB cheaper price ordering <- priceA <=> priceB negative = cheaper, zero = same, positive = more expensive
COALESCING
cheaper <- priceA <? priceB returns the lower price dearer <- priceA >? priceB returns the higher price
IMPORTANT: Comparison only works between same-currency Money values. Comparing 10#GBP with 20#USD returns unset — EK9 prevents accidental cross-currency comparison.
See Q35 for Money basics. See Q149 for currency safety. See Q243 for coalescing operators.
Example
defines module qa.operators.moneycompare defines function cheaperOf() as pure -> left as Money right as Money <- rtn as Money: left <? right dearerOf() as pure -> left as Money right as Money <- rtn as Money: left >? right defines program MoneyCompareDemo() stdout <- Stdout() // === MONEY LITERALS === priceA <- 29.99#USD priceB <- 45.50#USD sameAsA <- 29.99#USD // === COMPARISON === if priceA < priceB stdout.println("Price A is cheaper") require priceA < priceB require priceB > priceA require priceA == sameAsA require priceA <> priceB // === SPACESHIP ORDERING === ordering <- priceA <=> priceB stdout.println(`PriceA <=> PriceB: ${ordering}`) require ordering < 0 // === COALESCING: FIND CHEAPER AND DEARER === cheaper <- cheaperOf(priceA, priceB) dearer <- dearerOf(priceA, priceB) stdout.println(`Cheaper: ${cheaper}`) stdout.println(`Dearer: ${dearer}`) require cheaper == priceA require dearer == priceB // === STRING CONVERSION === priceStr <- $priceA stdout.println(`Price as string: ${priceStr}`) // === ISSET === require priceA? unsetMoney <- Money() require ~unsetMoney? // === COPY OPERATOR === backup <- 0.00#USD backup :=: priceA require backup == priceA stdout.println(`Copied price: ${backup}`)
Common mistakes
E50001 — EK9 has no Math type, so Math.min will not resolve (E50001); use the <? coalescing operator to select the lesser value. See ek9 -h E50001 for details.
Incorrect:
cheaper <- Math.min(priceA, priceB)
Correct:
cheaper <- cheaperOf(priceA, priceB)
Other ways to ask this
- Compare two Money values and select the lesser amount.
- I need to find the cheapest item from two prices using operators.
- In Java I used BigDecimal.compareTo for money — what does EK9 use?
Coming from another language?
Java: BigDecimal.compareTo(), no literal syntax, manual RoundingMode. Python: decimal.Decimal comparison. Rust: no built-in money type. Go: no built-in money type. EK9: 29.99#USD literals, direct < > == operators, <? coalescing, automatic HALF_UP rounding, cross-currency safety.
Keywords: currency, usd, price, cost, compare, operator, coalescing, gbp, money, cheaper