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?