Lurker News
Manipulating monetary amounts is a common computing chore. However, no mainstream language has a first-class data type for representing money, it’s up to programmers to code abstractions for it. This isn’t an issue per se until dealing with rounding issues from operations like installment payments (e.g., buy now, pay later), foreign exchange, or even simple things like fee processing and tax collection.

Inspired by my days at N26 Brasil dealing with these challenges, I introduce Money: a Kotlin library that makes monetary calculations and allocations easy.

Comments (228) 50 threads

Earlier comments
Etheryte3 replies#
Does this library handle rounding rules [0]? In many countries, prices are rounded to the nearest 5 cent, but the rules can often be elaborate. It looks like the allocation interface might support this, but at the moment I didn't find any mention of it without digging into the docs themselves.

[0] https://en.wikipedia.org/wiki/Cash_rounding

eriksencosta1 reply#
This is something I am aware but there is no support for this rounding scheme at the moment.
amluto3 replies#
Wait, how do you round? A fixed table from currency to minimum increment? You’re not about to find 1/100-Yen coins, for example.
vetinari4 replies#
You are not going to find 1 or 2 eurocents anymore either, but it is still a valid amount. You can pay that electronically, but not in cash.

So rounding for cash is a different problem that rounding money in general.

Continue this thread — 4 replies

graypegg#
I think one common feature of those rounding procedures is that they are only done for cash payments, rather than plastic, so rather than representing a monetary value, it would have to represent a payment specifically. (With knowledge of payment method and time of transaction since a lot of these rules had a start date.) Possibly a good library to extend off of this!
nsxwolf3 replies#
That provides the basis for solving precision and rounding issues but for a money library you need more abstractions. The ability to assign a currency code and supply conversion rates and convert between currencies at a minimum.
tightbookkeeper4 replies#
That’s an application design choice, not a minimum. An alternative is to work internally in one unit and convert at format time.
maest4 replies#
That is not a viable alternative.

Continue this thread — 4 replies

Phrodo_00#
Might be a minimum for a money library (not completely sure what the absolute minimum would be). It would be an application design choice to not use one and stick to general fixed point/Big Num constructs.
V41frQo1SccpfHI2 replies#
Out of curiosity, how do you deal with changing exchange rates in that case?

Continue this thread — 2 replies

knodi1231 reply#
We store all our financial data in Greenwich Mean Dollars.

Continue this thread — 1 reply

epolanski#
Also, avoid making errors like summing different currencies.
moomin1 reply#
The thing is, it doesn’t really help. A system I’m working on can have hundreds of monetary amounts in the same currency. Storing the currency against each one is an awful waste of space.

Equally the allocation trick is good, but you’ll find that the people who really care about this stuff really care about the exact algorithm you’re using and who it favours.

eriksencosta#
I think it helps to have the inputs and outputs of the system fully representing a "money" (i.e., a monetary amount + its currency code in places like API resources, events, and so on). This way you can internationalize or support multi-currency processing if that's the case. That's (if I remember correctly) what the payment card services companies (e.g., Mastercard, Visa) do by default in their message exchanges when calling the issuer for transaction confirmation.

Anyway, the allocation may be tweaked to favour where the additional/missing pennies will be allocated. You can find more at: https://github.com/eriksencosta/money/blob/trunk/docs/usage/...

owlstuffing3 replies#
Would be cool to hook this up as a manifold unit[1]. This way you could write code like:

Money ask = 2.1M USD;
What I don't see with the Java JSR is how exchange rate services are integrated (if at all?). In the best of worlds, as with manifold's units I could write.
Money deposit = 300 USD + 500 EUR;
Where internally the deposit automatically maintains the amounts separately and uses exchange rates only for spot display/calc, transfer, etc.
1. https://github.com/manifold-systems/manifold/tree/master/man...

willcipriano1 reply#
I'd like types for all the currencies.

USD rent = 2000
EUR salary = 6000.53
USD disposableIncome = salary - rent
Then:
disposableIncome.toDecimal()
disposableIncome.toInteger()
disposableIncome.toString()
USD interest = disposableIncome.compoundInterest(startDate, endDate, apy)
USD tip = billTotal.tip(percentage)
USD and EUR would inherit from Money
Not sure how to implement it, might be a JVM magic thing.

owlstuffing2 replies#
What you want is Money, currency is a _unit_ type of a Money quantity, just as meter is a unit type of Length.

Money cost = 25M USD;
cost += 12M EUR;
display(cost.to(EUR));

Continue this thread — 2 replies

wtetzner1 reply#
> Money ask = 2.1M USD;

Feels like it should be

  Money ask = 2.1M USD;
Then methods like .plus() wouldn't even be defined for incompatible currencies. Of course that doesn't work for .equals(), so you'd still have to fall back to exceptions in that case.
owlstuffing#
Generally, the idea is that there is no incompatibility between units. Money is a bit exotic given its abstract nature wrt units / exchange rates.

For instance, physical dimensions store values as SI units, regardless of supplied unit, but retain the supplied unit type as a display hint.
Here, the Length dimension illustrates working with amounts of any unit.
Length orbit = 250 mi;
Length moon = 238000 km;
Length landing = moon + orbit;
display(landing); // prints 148,136.344 mi
display(landing.to(km)); // prints 238,402.336 km
// where
display(landing.to(mi) == landing.to(km)); // prints true
// perhaps a better example
Rate rate = 1.41 km/s;
Time duration = 76 hours;
Length distance = rate * duration;
// make your own unit constants
RateUnit kps = km/s;
rate = 1.41 kps;
You can play with the manifold-science[1] project, it implements the complete SI physical dimensions and many derived dimensions along with comprehensive operator overloading[2] support etc. to make working with and reading code using quantities more productive in Java.
1. https://github.com/manifold-systems/manifold/tree/master/man...
2. https://github.com/manifold-systems/manifold/tree/master/man...

oftenwrong#
The JSR 354 API can provide access to exchange rate services via the ExchangeRateProvider interface. The reference implementation (Moneta) includes a few implementations of ExchangeRateProviders that connect to online services to look up exchange rates.
jeroenhd#
It will never not be funny to me how Java language designs have such a hatred for operator overloading yet will happily accept .multiply(2).add(something) as a substitute.
flykespice2 replies#
Except Kotlin is a multiplatform language now thanks to Jetbrains efforts (kmp project), it's not anymore intertwined with JVM.

Using Java library will limit your program only to jvm platform. Using a kotlin library like this one (given it's written in pure kotlin and doesn't uses any jvm platforms specifics) will allow you to build it to whatever target kmp supports (macosx, ios, android, js, mingw...)

jsiepkes#
> to build it to whatever target kmp supports (macosx, ios, android, js, mingw...)

Plenty of languages (also Java with Graal, TeaVM, J2CL, etc.) can also target these platforms.
But as with all these languages targeting these platforms (including Kotlin) you are going to have to call platform specific API if you want to do anything useful. There are also platforms specific limitations which means certain stuff which you can do in the language doesn't work on those platforms.

eriksencosta#
Not yet to Android (in the case of the library). Need to revamp some internal things.

Load more comments