I don't think that's correct, absent some no-true-scotsman gymnastics.
F# has units-of-measure (UoM) out of the box, and it supports decimal numbers. I've come across a python library for UoM as well.
The big problem with handling money in code is not, IMO, the rounding (your allocate function is a nice utility but it's not core); it's unit confusion - adding baht to ren mi bi, adding cents to euros, etc. This problem is very well solved by F#'s UoM.
Yeah, I think OP's claim is not valid. Even .NET provides System.Decimal, which by design and explicitly mentions financial calculations.
Taken from the intro docs:
https://learn.microsoft.com/en-us/dotnet/fundamentals/runtim...
> The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.
> The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.
We sometimes pretend that money is measuring something, but in reality it's much messier than that.
Neither does a money data type.
https://gist.github.com/williamcotton/b67ff641eeec7673131715...
https://www.joda.org/joda-money/
From the same person that brought us Joda Time (ie, what the java time API was based on). I've used Joda Money a lot and it's great.
Honestly I prefer APIs that look like APIs and I think this trend towards inventing DSLs is a bad one. Rails works because there's a critical mass of people who have adopted what is essentially a whole new language on top of Ruby. A money library doesn't warrant a new language, it's unnecessary cognitive load. This new money library would look fine with simple constructors and method calls.
Money.of(CurrencyUnit.USD, amount)
...everywhere and do a few other things like total Money instances.The examples were written using the infix notation but you can just use regular method calls. For example:
val price = Money.of(100, "USD")
val shipping = Money.of(5, "USD")
val subtotal = price.plus(shipping)
val discount = Percentage.of(10)
val total = subtotal.decreaseBy(discount)
total.allocate(2)
total.allocate(60.percent(), 40.percent())
I don't want to update my interpreter or compiler because Turkey changed their rules of daylight savings time, or Ethereum becomes popular.
They were just passed along.
These are largely things that can be handled by a library, but if it's in the language you best not get it wrong because it's so much harder to change!
Am I wrong here?
https://stackoverflow.com/questions/35326710/stripe-currency...
1. So many languages don't have a native "decimal" type to build off of, so somewhere in the data's lifecycle, a "1.75" turns into "1.7499999999997".
2. The rules around exchange rates, number of decimals, coding and symbols.
The first problem should be solved as a first-class language feature. This will discourage hacks with a "fixed point" type, where you store integer "175 cents" instead of decimal "$1.75"-- inviting huge confusion if the currency ever drops or restructures its minor unit, and supports non-money use cases where floating point inaccuracy is risky.
Item 2 makes more sense as a library. You can record that there's a 1000:1 ratio between pre-1998 and current roubles, that the symbol for the Baht will inevitably confuse Bitcoin enthusiasts, and that the Korean won no longer has any decimal places, in dynamic fields.
Everything is decided to be an 'abstraction' and it's someone else down the line that has to be concerned. Over the last 30 years of starting as a developer I've really lost faith that the majority are actually concerned with solving anything vs just indulging conceptual whims.
I think you're mixing up stuff that's unrelated to your concern.
The concerns you're expressing only apply to operations and financial transactions. That's not handled by spreadsheets, browsers, or databases. In fact, the primary concern of a browser is to provide views over data fed by servers.
In addition, it sounds like you're confusing minor conveniences with something being somehow broken by design. The reason why no one bothered to standardize a money type is the fact that there isn't a technical requirements for it at all.
Manipulating money is probably trickiest thing since time was invented. Library looks very usable.
I have to ask though:
> val transactionFee = 1.25.percent() // 1.5%
How is it 1.5?
References:
Brazil: https://blog.eriksen.com.br/en/platform-engineering-n26 Europe: https://medium.com/insiden26/engineering-at-n26-a-tour-of-ou...
(see roundN)
Be careful and use it only if you know what you are doing and understand the limitations.
I beg to differ. Java has "Decimal" class which guarantees to be safe from IEEE754 floating number side effects, and specially created to handle cases like money and financial calculations.
In these days it's used as BigDecimal, it seems [1].
[0]: https://docs.oracle.com/javase/8/docs/api/java/text/DecimalF... [1]: https://docs.oracle.com/en/java/javase/23/docs/api/java.base...
A library built upon it can be found here [1].
Decimals aren't enough. You have frequent currency conversions and all sorts of other chores. Using a fixed-decimal datatype doesn't solve those problems by itself, it's just a tactic.
Yes, I never worked in fintech, but lots of my family members work or worked in banking sector. So, I'm not an alien when it comes to money, and how it works and processed in IT side of the things.
I'm fairly sure that for example for RON, the Romanian Central Bank only publishes daily rates, for example.
This is literally the entire point of COBOL
The core systems of many old institutions still relies heavily on COBOL.
[1] https://jcp.org/en/jsr/detail?id=354 [2] https://javamoney.github.io/
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...
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.
Money cost = 25M USD;
cost += 12M EUR;
display(cost.to(EUR));
> just as meter is a unit type of Length
The difference is that length units are fixed, but exchange rates are constantly changing.
Right. As I mentioned earlier exchange rate services would need to be integrated into the API.
Also, exchange rate services would not be needed until a conversion is necessary. For instance, when adding money of different currencies internally the Money type maintains currencies separately, subtotals for USD, EUR, etc. are managed. If at a later time the sum of Money should be displayed, deposited, etc. as a single currency, only then is an exchange service involved.
Feels like it should be
Money<USD> 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.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...
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...)
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.
https://www.rebol.com/docs/core23/rebolcore-16.html#section-...
> $100 + 11 $111.00
> $10 / .50 $20.00
In general, Rebol's type system was very expressive. Would love to see more libraries like this provide that type of experience.
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.
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/...
The OP just described a language feature where you want to multiply euros with usd one place and yen and dinar in another.
You don’t need to do that which is why a decimal or 64 bit int is a fine language approach.
Sometimes you can do all calculations in a single currency and convert at reporting time. I've worked on teams where that was fine.
Sometimes... you really cannot do that.
This one seems to carry units, as in, it is not a type with math for a known amount of fixed point precision that differentiates this library, but that it captures that plus the unit -- the currency, USD, EUR, etc -- that it is in.
- Let's say I load two money values from a database. Value A is 1 USD and value B is 1 BTC. If I try to add them together, what happens? (I would expect a runtime exception. In fact, I would hope for a runtime exception, because the operation usually indicates a programming error.)
- If I divide $2.00 by 3, do I get $0.66 or $0.67? If I want to specify the rounding rule, is there a simple way to do it? I see there's support for allocation by percentage, but sometimes the allocation rules are more complex and I need to be able to specify the rounding rule.
- Does this library help parse user input? When parsing user input, what happens to extra digits? Does "0.015" get interpreted as $0.01 or $0.02?
Edit: one more question. Sometimes people bend the rules on the number of digits; for example, gas stations may charge $3.599 per gallon. Can the library deal with that or would I have to convert to decimal, multiply, and then convert back to money?
1. You get an exception
2. You may specify the rounding rule: https://github.com/eriksencosta/money/blob/trunk/docs/usage/...
3. It has some parsing capabilities. The extra digit is kept, rounding is only applied when doing an operation with the Money object
4. Same as 2
1) A hint about potential prior art: F# (and/or C#?) have a first-class unit system (physical units I think), which sounds a bit similar to monetary calculations. However, physical unit are easier to model than monetary unit I think.
2) Currently, I am building something tangentially related in Rust: A backtester (test trading strategies on historical and/or simulated data) with focus on accuracy. So one thing I included already is that Assets (like etfs) are valued in a currency.
If I may be so bold: How would you approach these questions / where could I read more about that? 1) When simulating, can I always assume that the exchange will work? (For assets, that is not always the case, sometimes one has to wait a bit until there is a buyer, or there might not be a buyer at all) 2) Is there public domain data in exchange rates? 3) If I have to choose, which exchange rate should I pick? The lower one, higher? What would make the most sense in the context of trading etfs, stocks, options, crypto etc.? 4) How to approach rounding, is there a best practise? 5) I assume it is best to immediately substract taxes in every transaction, even if they are formally defined annually, right? 6) Would you model inflation? I currently plan to ignore it and present it at the very end: "Your portfolio has a final value of X.X ¥. Adjusted for inflation, that would be Y.Y ¥ today (2024-10-08)."
val amount = 1 money "USD" // USD 1.00
val rate = 5.4905 money "BRL" // BRL 5.4905
amount exchange rate // BRL 5.49
It's up to implementers to hook up in other datasets and to consume the rates. Exchange rates datasets differ from country to country and some foreign exchange companies offer short-term contracts to hold a transaction at a given rate (sort of "guaranteed rate/price"). I don't see myself supporting this use case.
Nevertheless, Java Money (Moneta) has this feature. Never used it so, I don't know how it works.
I think it makes sense that this feature would not be planned in your library - as I understand, its goal is to support developers to write better money-related logic, which is sometimes related but different from simulating as accurately as possible.
I just noticed a potential misuse of your API: Transitve relationships: "A" = 2.0000 "B", and "B" = 3.0000 "C", then implicitely, "A" = 6.0000 "C". Can the user now define "A" = 7.0000 "C"?
That would be wrong - but not trivial to prevent, and practically speaking, it is okay I think.
Thank you for your time and for this exchange, wish you good success and fun with kotlin money! :)
With that we can go back to the example:
"A" = 2.0000 "B"
"B" = 3.0000 "C" -> "A" = 6.0000 "C"
"A" = 7.0000 "C"
If you notice this happening in the real world, you have the opportunity to:
1. buy 7 "C" with 1 "A"
2. buy 2 "B" with 6 "C"
3. buy 1 "A" with 2 "B"
4. keep 1 "A" profit
But it's rarely that simple and it often involves 3 or more currencies
Inspired by my days at N26 Brasil dealing with these challenges, I introduce Money: a Kotlin library that makes monetary calculations and allocations easy.