OliverNChalk / const-decimal

Integer-backed decimals with constant precision
Apache License 2.0
1 stars 1 forks source link

Is it planned to implement cross decimal numeric ops? #10

Open MathisWellmann opened 2 days ago

MathisWellmann commented 2 days ago

In principle something like:

impl<I, const D: u8, const D_RHS: u8> std::ops::Mul<Decimal<I, D_RHS>> for Decimal<I, D>{}

which would allow two decimals of differing constant decimal range to nicely compose together. This does not compile, so we'd need another mechanism such as a new trait which does the conversion and numeric operation explicitly, thus avoiding confusion as well. Obviously the operations would apply the proper scaling to ensure correctness.

The usecase I'm considering this for is in lfest-rs, e.g for multiplying a currency denoted in BaseCurrency(Decimal<I, D>) by a fraction denoted in BasisPoints(Decimal<I, 4>). But more generally this could be useful for computing a percentage (Decimal<u32, 2>) of a value with a different constant decimal point.

Is this is something you would consider accepting into the code? I'd be happy to create a pull request for it.

OliverNChalk commented 2 days ago

Hi Mathis, this is indeed something I have considered but skipped over as my original use case was a uniform scaling across my trading system. However, unfortunately crypto exchanges insist on using very strange step sizes etc so that experiment failed. Hence I've now needed to add https://github.com/OliverNChalk/const-decimal/tree/feat/dyn-decimal to give me a wider range of support.

I think https://crates.io/crates/fixed implements a similar mechanism to what you're talking about but that is unfortunately in base2 so not useful for financial applications.

I would definitely accept a PR adding this. Let me first merge the dyn-decimal branch as it converts the repo into a workspace. Otherwise if you start working you'll get some merge conflicts if I do merge dyn-decimal.

MathisWellmann commented 2 days ago

Sounds good to me. I'll experiment with my idea for a bit first and will let you know how it turns out.