I'm trying to implement a daily interest rate calculation in Solidity based on an annual interest rate, but I'm facing issues with the precision of fractional numbers. Here's the calculation I'm using:
uint256 private constant ANNUAL_INTEREST_SCALE = 1e9;
uint256 private constant ANNUAL_INTEREST_PERCENT = 2;
uint256 public constant DAILY_INTEREST_RATE = (ANNUAL_INTEREST_PERCENT * ANNUAL_INTEREST_SCALE) / 365;
Given the constants above, the daily interest rate I calculated is 5479452
when scaled by 1e9
. However, when I want to apply this rate to calculate rewards, it seems too high because Solidity does not handle fractional numbers. The real value I'm aiming which is 2/365 = 0.005479452
.
Lets say one day 2% annual interest calculated without solidity is:
1 day interest = 2 / 365 = 0.005479452
And 1 day interest in solidity is:
5479452
Lets say reward formula is:
rewardTokens for 1 day is = 5479452 * depsositAmount = 5479452 * 1 Token = 5479452
Solution:
so reward is 5479452
which is usually in Wei in remix, we can convert into Gwei via web3.js which will be equal to 0.005479452 Gwei.