0

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.


  1. Lets say one day 2% annual interest calculated without solidity is:

    1 day interest = 2 / 365 = 0.005479452

  2. And 1 day interest in solidity is: 5479452

  3. 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. enter image description here

5
  • 1
    Show the code used to calculate the rewards. When using fixed point arithmetic you have to be careful about the operation order.
    – Ismael
    Commented Jun 3 at 19:39
  • correct @Ismael Commented Jun 4 at 8:06
  • @Ismael could you please check mine answer on it that i finally got ? Commented Jun 4 at 8:10
  • 1
    I still don't understand what was your problem. In fixed point arithmetic number are multiplied by a large scale factor (10^9 in your case). To get the real value they have to divided by the same factor. This is usually calculated in the UI code.
    – Ismael
    Commented Jun 4 at 14:23
  • Yess correct @Ismael Commented Jun 4 at 15:00

1 Answer 1

1
  1. Lets say one day 2% annual interest calculated without solidity is:

    1 day interest = 2 / 365 = 0.005479452

  2. And 1 day interest in solidity is: 5479452

  3. 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. enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.