News for hackers. Stuff that matters.
Re:Ask HN: How to handle financial calculations precisely? by Leftium on Wednesday January 25, 2023 @06:31PM (#34525690)
Dinero stores three pieces of data with a dynamic scale: https://v2.dinerojs.com/docs/core-concepts/amount

- amount: expressed in the smallest subdivision of the currency, as an integer.

- currency: unique code, base, and exponent

- scale: conceptually close to the currency exponent but serves the purpose of expressing precision as accurately as possible.

---

Multiply[1]: If you need to multiply by a fractional multiplier, you shouldn't use floats, but scaled amounts instead. For example, instead of passing 2.1, you should pass { amount: 21, scale: 1 }. When using scaled amounts, the function converts the returned objects to the safest scale.

Allocate[2] (alternative to dividing): Distribute the amount of a Dinero object across a list of ratios.

[1]: https://v2.dinerojs.com/docs/api/mutations/multiply

[2]: https://v2.dinerojs.com/docs/api/mutations/allocate

There are no comments on this comment yet.