In the given scenario that I have the following code, in which a user sets a token amount and an ETH amount, I want to determine a price of token using the following code:

pricePerToken = (ethAmount * 1e18) / tokenAmount;

This divides the ethAmount in wei by the tokenAmount, and should give the price per token.

For example, if the ethAmount in Wei is 1000000000000000, And the tokenAmount with 18 decimals is 47500000000000000000 (47.5 tokens), The price per token is 21052631578947 wei, or 0.000021052631578947 ETH

The contract simply fulfills a token amount based on the msg.value at a rate determined by the pricePerToken. However, when I attempt to trade 0.000021052631578947 ETH to purchase 1 token in this scenario, it purchases 0.9999999999999825 tokens instead of 1 token, leaving a very tiny fraction behind.

Is there any possible way to avoid this when the numbers of tokens or ETH dealt with can potentially be extremely small?

  • You may need a fixed-point math library. I recommend using PRBMath. Commented Sep 5, 2023 at 10:32

1 Answer 1


There are multiple ways of avoiding it

The most obvious one would be to use higher scaling up the conversion parameters.

You can use 30 decimals for calculation (1e30) instead of 18 decimals (1e18).

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.