News for hackers. Stuff that matters.
Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @08:59AM (#41776879)
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.

Re:Kotlin Money by psd1 on Tuesday October 08, 2024 @10:09AM (#41777558)
> no mainstream language has a first-class data type for representing money

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.

Re:Kotlin Money by chipdart on Tuesday October 08, 2024 @12:02PM (#41778859)
> I don't think that's correct, absent some no-true-scotsman gymnastics.

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.

Re:Kotlin Money by nostrademons on Tuesday October 08, 2024 @12:14PM (#41778965)
This is often not what you want with monetary calculations. You want the rounding: you'll be making a payment of $25.86, not $25.85714285714... But you just want to make sure that the next payment is $25.85, not $25.86 or $25.857142851, and that all 7 payments together equal $181 and not $181.02.
Re:Kotlin Money by explorigin on Tuesday October 08, 2024 @12:41PM (#41779223)
I can't speak for C# but the Python Decimal type handle significant figures correctly.

> 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.

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @02:34PM (#41780359)
Languages indeed have support for currencies and decimal numbers. My implementation is based on Fowler's Money pattern. The Money object is thus a value object representing a monetary amount in a given currency.

https://martinfowler.com/eaaCatalog/money.html

Re:Kotlin Money by __MatrixMan__ on Tuesday October 08, 2024 @10:27AM (#41777760)
I don't know either well, but I took a glance at both and it doesn't seem like UoM is well set up for making decisions based on which peer is going to give you a better exchange rate.

We sometimes pretend that money is measuring something, but in reality it's much messier than that.

Re:Kotlin Money by chipdart on Tuesday October 08, 2024 @12:05PM (#41778887)
> (...) making decisions based on which peer is going to give you a better exchange rate.

Neither does a money data type.

Re:Kotlin Money by __MatrixMan__ on Tuesday October 08, 2024 @03:15PM (#41780745)
It looks like multiple exchange rates per currency pair is supported: https://github.com/eriksencosta/money/blob/4bef95a1d2158e308...
Re:Kotlin Money by oblio on Tuesday October 08, 2024 @10:16AM (#41777624)
Ok, what do I do in F# if I want to not think about the low level details of FX conversions, rounding, etc? Which libraries can I use?
Re:Kotlin Money by slekker on Tuesday October 08, 2024 @11:55AM (#41778775)
Sounds interesting! How would it look like? Do you have some code to share?
Re:Kotlin Money by williamcotton on Tuesday October 08, 2024 @12:25PM (#41779070)
Re:Kotlin Money by hiddew on Tuesday October 08, 2024 @09:56AM (#41777430)
How does it compare to the Java money API (https://jcp.org/en/jsr/detail?id=354) and the related Kotlin DSL in https://github.com/hiddewie/money-kotlin/?tab=readme-ov-file...?
Re:Kotlin Money by stickfigure on Tuesday October 08, 2024 @10:39AM (#41777855)
I'm surprised nobody has mentioned Joda Money yet:

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.

Re:Kotlin Money by nogridbag on Tuesday October 08, 2024 @12:46PM (#41779272)
I personally went with Joda money versus the Java money API mentioned above. Our needs are a bit simpler and the Joda Money API is a bit simpler to understand. Our app only deals in USD so I wrote a small utility class to help initialize Money instances so devs don't have to write:

    Money.of(CurrencyUnit.USD, amount)
...everywhere and do a few other things like total Money instances.
Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @02:27PM (#41780290)
Joda is impressive and has great performance.

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())

Re:Kotlin Money by rafaelferreira on Tuesday October 08, 2024 @10:27AM (#41777756)
Another library in this space is Eric Evans' (of DDD fame) Time & Money library https://timeandmoney.sourceforge.net/.
Re:Kotlin Money by getfroggie on Tuesday October 08, 2024 @09:32AM (#41777196)
It's kind of strange that spreadsheet languages don't support money well. Using spreadsheets for escalator style automation is actually quite good and would really be amazing in a language that took typing seriously.
Re:Kotlin Money by ebiester on Tuesday October 08, 2024 @09:57AM (#41777447)
I think there's a good reason for it to be part of a library. The problem with currencies is much like dates: they're a social construct, and change more than most of the social constructs we embed in programming languages.

I don't want to update my interpreter or compiler because Turkey changed their rules of daylight savings time, or Ethereum becomes popular.

Re:Kotlin Money by JumpCrisscross on Tuesday October 08, 2024 @12:21PM (#41779035)
Oh, this reminds me of my first job out of college at a Swiss bank. Apparently every time a currency conversion was done in a particular model, there was a routine that translated back and forth between the pre-Euro currency and Euro at the conversion rate. So a USD-EUR transaction with a party in France would be run as USD-FRF --> FRF-EUR. All in COBOL. As a result, every so often, you'd get a slightly different result running a USD-EUR trade with a party in France versus e.g. Germany or the U.K.
Re:Kotlin Money by tomcam on Tuesday October 08, 2024 @01:41PM (#41779842)
So what happened when those discrepancies arose?
Re:Kotlin Money by tvaughan on Tuesday October 08, 2024 @02:36PM (#41780375)
They became the basis for the plot of Superman III
Re:Kotlin Money by JumpCrisscross on Tuesday October 08, 2024 @02:27PM (#41780288)
> what happened when those discrepancies arose?

They were just passed along.

Re:Kotlin Money by skybrian on Tuesday October 08, 2024 @12:03PM (#41778869)
You could say the same of Unicode, though. Some cultural abstractions become increasingly rigid because they’re embedded in computer systems everywhere.
Re:Kotlin Money by coreload on Tuesday October 08, 2024 @10:13AM (#41777592)
Yes, and sometimes the context is not just social but legal or contractual, e.g. rounding currency.
Re:Kotlin Money by ebiester on Tuesday October 08, 2024 @10:21AM (#41777685)
Yes, and rounding currency is just something that is always handled, as is the number of places that you take a currency out to - for example, gas is often priced at thousandths of a dollar rather than hundreds but presented to the customer in hundredths at the end. Or Yen in most cases does not have a decimal point, except that the places where you round or don't round can be consequential in large enough quantities.

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!

Re:Kotlin Money by benatkin on Tuesday October 08, 2024 @01:13PM (#41779517)
From my perspective those are tenths of a cent. Stripe has integer values for cents.

Am I wrong here?

https://stackoverflow.com/questions/35326710/stripe-currency...

Re:Kotlin Money by carapace on Tuesday October 08, 2024 @11:37AM (#41778544)
This. But more than being changeable they (time and money) are supra-logical or trans-rational. In other words, computers are limited to what can be modeled or calculated with the one logical operation (it has lots of names, I like "Quine dagger") but these phenomenon are not.
Re:Kotlin Money by hakfoo on Saturday October 12, 2024 @02:29PM (#41821274)
There's two problems with currencies:

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.

Re:Kotlin Money by weego on Tuesday October 08, 2024 @11:50AM (#41778713)
Spreadsheets, browsers, databases.

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.

Re:Kotlin Money by chipdart on Tuesday October 08, 2024 @12:18PM (#41779010)
> Spreadsheets, browsers, databases.

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.

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @09:37AM (#41777237)
I couldn't agree more as someone who has been using more spreadsheets than actually coding in the last 10 years.
Re:Kotlin Money by Ygg2 on Tuesday October 08, 2024 @09:31AM (#41777190)
Nice library!

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?

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @09:32AM (#41777201)
Oh sorry, that's a typo. Thanks for pointing out!
Re:Kotlin Money by stefs on Wednesday October 09, 2024 @04:33AM (#41785726)
except for manipulating time, i'd say
Re:Kotlin Money by sandGorgon on Tuesday October 08, 2024 @09:28AM (#41777144)
just curious - what is the backend api framework that N26 uses ? is it kotlin specific ? or generically spring boot or something ?
Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @09:34AM (#41777212)
In Brazil (where I worked) we used Kotlin + Ktor. In Europe, they are heavy Kotlin users.

References:

Brazil: https://blog.eriksen.com.br/en/platform-engineering-n26 Europe: https://medium.com/insiden26/engineering-at-n26-a-tour-of-ou...

Re:Kotlin Money by atemerev on Tuesday October 08, 2024 @09:27AM (#41777139)
Cool! As underlying values, do you use integers, bigdecimals, or a decimalized double hack like in OpenHFT?
Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @09:32AM (#41777198)
It uses BigDecimal. My first goal with the library was to provide a well-designed API. So to keep it simple for myself, I relied on BigDecimal for the calculations.
Re:Kotlin Money by atemerev on Tuesday October 08, 2024 @09:45AM (#41777315)
I think you are right, API is the most important part; internal implementation can be optimized later.
Re:Kotlin Money by vamega on Tuesday October 08, 2024 @01:03PM (#41779436)
What is the double hack used in OpenHFT? I tried looking this up and came up short.
Re:Kotlin Money by pcl on Tuesday October 08, 2024 @06:03PM (#41782251)
I’ll byte. Perhaps you didn’t look long enough. I’m sure the answer will float by at some point.
Re:Kotlin Money by atemerev on Wednesday October 09, 2024 @04:08AM (#41785597)
https://github.com/OpenHFT/Chronicle-Core/blob/ea/src/main/j...

(see roundN)

Be careful and use it only if you know what you are doing and understand the limitations.

Re:Kotlin Money by bayindirh on Tuesday October 08, 2024 @09:58AM (#41777460)
> However, no mainstream language has a first-class data type for representing money...

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...

Re:Kotlin Money by jeremyjh on Tuesday October 08, 2024 @10:06AM (#41777523)
Can BigDecimal tell me which currency a monetary value is denominated in?
Re:Kotlin Money by bayindirh on Tuesday October 08, 2024 @10:10AM (#41777569)
No, but Java has a specification (JSR 354) to build money and currency APIs [0].

A library built upon it can be found here [1].

[0]: https://jcp.org/en/jsr/detail?id=354

[1]: https://javamoney.github.io/

Re:Kotlin Money by mhluongo on Tuesday October 08, 2024 @10:09AM (#41777557)
Tell me you've never worked in fintech without telling me you've never worked in fintech :)

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.

Re:Kotlin Money by bayindirh on Tuesday October 08, 2024 @10:11AM (#41777575)
See JSR-354 then: https://jcp.org/en/jsr/detail?id=354

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.

Re:Kotlin Money by boronine on Tuesday October 08, 2024 @09:58AM (#41777450)
I think most of this is covered by a good Decimal API, currency stuff probably shouldn't be embedded into a language because it changes: currencies come and go, get redenominated etc. Although one simple thing that would be useful is keeping track of abstract units, e.g. throwing an error when attempting to do 10 USD + 10 EUR.
Re:Kotlin Money by oblio on Tuesday October 08, 2024 @10:16AM (#41777625)
Don't we embed timezones, though?
Re:Kotlin Money by explorigin on Tuesday October 08, 2024 @12:42PM (#41779236)
Timezone conversions don't change by the minute. Currency conversions do.
Re:Kotlin Money by oblio on Wednesday October 09, 2024 @02:23PM (#41791054)
Do most applications use the minute-to-minute conversions or some daily rate?

I'm fairly sure that for example for RON, the Romanian Central Bank only publishes daily rates, for example.

Re:Kotlin Money by shortrounddev2 on Tuesday October 08, 2024 @09:38AM (#41777238)
> However, no mainstream language has a first-class data type for representing money

This is literally the entire point of COBOL

Re:Kotlin Money by millerm on Tuesday October 08, 2024 @09:40AM (#41777259)
"no mainstream language..." COBOL is has not been a mainstream language for many decades now.
Re:Kotlin Money by wiether on Tuesday October 08, 2024 @09:42AM (#41777285)
It's still quite mainstream in domains where they manipulate a lot of money : banking/insurance.

The core systems of many old institutions still relies heavily on COBOL.

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @09:57AM (#41777441)
I think I will add a footnote on COBOL. COBOL is huge in Brazil, lot of insurance/financial companies are still using mainframes.
Re:Kotlin Money by throw16180339 on Tuesday October 08, 2024 @02:09PM (#41780106)
There are billions of lines of COBOL in production. It's not going away any time soon.
Re:Kotlin Money by jsiepkes on Tuesday October 08, 2024 @12:20PM (#41779029)
Java has JSR 354 for money [1]. There is also a reference implementation [2]. So there is official support for money in Java.

[1] https://jcp.org/en/jsr/detail?id=354 [2] https://javamoney.github.io/

Re:Kotlin Money by owlstuffing on Tuesday October 08, 2024 @01:40PM (#41779825)
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...

Re:Kotlin Money by willcipriano on Tuesday October 08, 2024 @03:55PM (#41781183)
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.

Re:Kotlin Money by owlstuffing on Tuesday October 08, 2024 @05:32PM (#41782033)
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));

Re:Kotlin Money by wtetzner on Wednesday October 09, 2024 @12:15AM (#41784451)
I don't think this makes sense? You need to specify an exchange rate somewhere.

> just as meter is a unit type of Length

The difference is that length units are fixed, but exchange rates are constantly changing.

Re:Kotlin Money by owlstuffing on Wednesday October 09, 2024 @01:55AM (#41784918)
> You need to specify an exchange rate somewhere.

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.

Re:Kotlin Money by wtetzner on Wednesday October 09, 2024 @12:12AM (#41784444)
> Money ask = 2.1M USD;

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.
Re:Kotlin Money by owlstuffing on Wednesday October 09, 2024 @02:45AM (#41785169)
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...

Re:Kotlin Money by oftenwrong on Wednesday October 09, 2024 @03:31PM (#41791746)
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.
Re:Kotlin Money by jeroenhd on Wednesday October 09, 2024 @02:47AM (#41785180)
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.
Re:Kotlin Money by flykespice on Wednesday October 09, 2024 @11:47AM (#41789203)
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...)

Re:Kotlin Money by jsiepkes on Thursday October 10, 2024 @08:21AM (#41798118)
> 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.

Re:Kotlin Money by eriksencosta on Friday October 11, 2024 @01:35AM (#41806502)
Not yet to Android (in the case of the library). Need to revamp some internal things.
Re:Kotlin Money by wiremine on Tuesday October 08, 2024 @12:35PM (#41779155)
Nice! Reminds me of the ergonomics of Rebol's money type:

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.

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @02:28PM (#41780299)
This is great!
Re:Kotlin Money by yett on Tuesday October 08, 2024 @12:57PM (#41779381)
C# has a decimal type: "The decimal type is a 128-bit data type suitable for financial and monetary calculations." https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
Re:Kotlin Money by nsxwolf on Tuesday October 08, 2024 @01:35PM (#41779763)
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.
Re:Kotlin Money by moomin on Tuesday October 08, 2024 @04:17PM (#41781424)
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.

Re:Kotlin Money by eriksencosta on Friday October 11, 2024 @01:30AM (#41806478)
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/...

Re:Kotlin Money by epolanski on Tuesday October 08, 2024 @02:49PM (#41780488)
Also, avoid making errors like summing different currencies.
Re:Kotlin Money by tightbookkeeper on Tuesday October 08, 2024 @01:54PM (#41779965)
That’s an application design choice, not a minimum. An alternative is to work internally in one unit and convert at format time.
Re:Kotlin Money by knodi123 on Tuesday October 08, 2024 @04:04PM (#41781282)
We store all our financial data in Greenwich Mean Dollars.
Re:Kotlin Money by irq-1 on Tuesday October 08, 2024 @05:14PM (#41781894)
What are you going to do about the new Moon Dollars?
Re:Kotlin Money by Phrodo_00 on Tuesday October 08, 2024 @03:28PM (#41780883)
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.
Re:Kotlin Money by V41frQo1SccpfHI on Tuesday October 08, 2024 @03:36PM (#41780979)
Out of curiosity, how do you deal with changing exchange rates in that case?
Re:Kotlin Money by amoshebb on Tuesday October 08, 2024 @05:15PM (#41781897)
it depends, if it was a currency exchange, it'll be labeled in one of 3 ways, either average rate per unit, absolute, or it'll be a reference to a MSSQL table containing exceptional spot transactions. Otherwise, a complete history of exchange rates is stored in KDB, most days you can take the average, and for small amounts on weekends or days the exchange is closed you can just interpolate, there's also a half dozen XLSXs full of certain exceptional days, so you'll have to check that you're not on one of those lists. Then if you're not dealing with USD->X or CAD->USD->X things start to get hairy.
Re:Kotlin Money by tightbookkeeper on Wednesday October 09, 2024 @12:00AM (#41784409)
You never want to be lossy with user inputs. Save what they told you and then convert for internal logic.

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.

Re:Kotlin Money by maest on Tuesday October 08, 2024 @02:12PM (#41780145)
That is not a viable alternative.
Re:Kotlin Money by serial_dev on Tuesday October 08, 2024 @02:29PM (#41780314)
Even though my gut reaction is to agree with you, it’s true that it is an app design decision, so in certain scenarios it might very well be a good design decision.
Re:Kotlin Money by tightbookkeeper on Tuesday October 08, 2024 @03:27PM (#41780879)
Shipped applications disagree with you.
Re:Kotlin Money by dmoy on Tuesday October 08, 2024 @03:53PM (#41781166)
It really depends on the context of the app

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.

Re:Kotlin Money by tightbookkeeper on Tuesday October 08, 2024 @04:09PM (#41781331)
Completely agree.
Re:Kotlin Money by sgt on Tuesday October 08, 2024 @01:22PM (#41779611)
What's the best library for JS or TypeScript?
Re:Kotlin Money by vintagedave on Tuesday October 08, 2024 @01:27PM (#41779669)
Delphi has a currency type, as does C++Builder (so, a native Currency type available in C++ with that toolchain.)

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.

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @02:32PM (#41780346)
You are right. Languages indeed have support for currencies and decimal numbers. My implementation is based on Fowler's Money pattern. The Money object is thus a value object representing a monetary amount in a given currency.
Re:Kotlin Money by hathawsh on Tuesday October 08, 2024 @01:42PM (#41779858)
I have questions about some edge cases I've encountered in dealing with money.

- 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?

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @02:23PM (#41780249)
Thanks for the questions. Answers:

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

Re:Kotlin Money by proper_elb on Tuesday October 08, 2024 @02:01PM (#41780037)
First, congrats on the library and thank you for sharing it!

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)."

Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @03:12PM (#41780722)
The currency exchange support is way simpler than this. The library only provides a method that will calculate the monetary amount given another Money object as the rate:

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.

Re:Kotlin Money by proper_elb on Tuesday October 08, 2024 @05:32PM (#41782040)
Thank you for your insights!

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! :)

Re:Kotlin Money by alluringorange on Thursday October 10, 2024 @01:16AM (#41795752)
Exchange rates are often not perfectly aligned, even if for a short periods of time. This is where arbitrage comes into play and levels the market.

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

Re:Kotlin Money by kens on Tuesday October 08, 2024 @03:00PM (#41780601)
The IBM 1401 mainframe (1959) optionally supported pounds/shillings/pence (£sd) arithmetic in hardware. In those days, there were 12 pence in a shilling and 20 shillings in a pound, so arithmetic with UK money was non-trivial. (This wasn't even microcode; this was literally boards full of transistors to add, subtract, multiply, divide, and format currency values.)
Re:Kotlin Money by eriksencosta on Tuesday October 08, 2024 @03:13PM (#41780732)
I love to learn more about the history of computing. Thanks.