简体   繁体   中英

Handling precision with money and interest rate calculation

I'm writing a small system that requires many calculations on top of money amounts and interest rates. I'm using Martin Fowler's Money to represent my money amounts, but i'm not sure how to represent the interest rates properly. Also, how can i make interest rate calculation with my integers?

i think the rate representation is rather simple: immutable, infinite precision rational number with references to 2 currencies. if you do something complex you may need a timestamp and an 'owner' as rates varies in time and each institution can have it's own rates. but i would keep those values outside of the rate entity itself. just remember not to assume any consistency in rates. as going from currency A to B through C may give you a different results than going from A to B through D. and also the dictionary of 'active' currencies is not constant

When representing interest rates, you have the same constraints as for monetary values, that is, floating point is not an appropriate representation and you need to do decimal values that retain full precision. Unlike most monetary values, your interest rate may need more than 2 decimals places of precision.

When multiplying interest rates by monetary values, you need to make sure you never touch nor convert to float. Generally with all libraries implementing decimal, you can perform operations between decimals or decimals and integers and obtain decimal results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM