Reference · Decimals and money
money.compare
signature
money.compare(map, map) -> intWhat it does
How two amounts of one currency stand: -1 when the first is smaller, 0 when they
are equal, 1 when it is larger. Comparing across currencies is a runtime error, as
is adding them. Use it where < and > would be used on numbers: is the balance
enough, is the total over the limit.
Examples
let a = money.of("10.25", "USD")let b = money.of("0.75", "USD")print(money.compare(a, b), money.compare(b, a), money.compare(a, a))print(money.compare(a, b) > 0, money.compare(money.of(-1, "USD"), money.zero("USD")))output
1 -1 0true -1Edge cases
- Zeros at the end do not count:
10.25and10.250compare equal. - A map made by hand or read from JSON compares too, read as
money.ofreads an amount: an int or numeric text, the code trimmed and in any case. More decimals than the currency has is a runtime error, so1.005dollars is never more than1.00: round it first withmoney.round. - For a sort,
sort_byon theamountis simpler;money.compareis for one decision.
let a = money.of("10.25", "USD")print(money.compare(a, { amount: "10.250", currency: "usd" }))let enough = money.compare(money.of(50, "USD"), a) >= 0print(enough)print([money.of(3, "USD"), money.of(1, "USD"), money.of(2, "USD")] | sort_by((m) => m.amount) | map((m) => m.amount))output
0true[1.00m, 2.00m, 3.00m]Errors
Two currencies, or a value that is not money (a map with more decimals than its currency has, too), are runtime errors, not error values.
this one fails
print(money.compare(money.of(1, "USD"), money.of(1, "EUR")))output
line 1: cannot compare USD and EUR: convert one currency to the other firstthis one fails
print(money.compare(money.of(1, "USD"), { amount: "1.005", currency: "USD" }))output
line 1: `money.compare`: 1.005 has more decimals than USD has (2): round it first with money.round(m, mode)Chaining
let limit = money.of(100, "USD")print(money.of(120, "USD") | money.compare(limit))print([money.of(120, "USD"), money.of(80, "USD")] | filter((m) => money.compare(m, limit) > 0) | len)output
11See also
money.is_zero, money.sub, money.add, sort_by
Thread
Thread 0 posts
On money.compare(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo