How to factor in decimals when using division and remainders

math is not my strong suite so I have a question for anyone that understands solidity's mathematical operations.

_

I have the following situation:

• Token is priced at 0.001 Ethereum.
• Token has 18 decimals.

Example purchase A (code at the bottom):

• Person A deposits 0.01 Ethereum.

• Amount deposited divided by price is 10.

• So Person A gets 10 tokens, but we have 18 decimals. So it should be 10e18, not 10. How do we get this? (see code)

_

Example purchase B (code at the bottom)

• Person B deposits 0.0001 Ethereum
• Amount deposited divided by price should be 0.1 if done on a calculator, but a simple division in solidity only returns 0. I understand this is due to solidity not denoting decimals by a dot notation, so the answer should ultimately become 1e17

Code situation A

function FooBar() public returns (uint){
// 1 Token will cost 0.001 eth.
uint256 _tokenPrice = 1e15;

// Incoming ethereum is 0.01.
uint256 _ethereumSent = 1e16;

// This should net us 10 tokens.
uint256 _totalTokens = _ethereumSent / _tokenPrice;

// So this returns 10, but we want 1e19 because of the fact that our token has 18 decimals.
return _totalTokens;
}

Code situation B

function FooBar() public returns (uint){
// 1 Token will cost 0.001 eth.
uint256 _tokenPrice = 1e15;

// Incoming ethereum is 0.0001.
uint256 _ethereumSent = 1e14;

// This should net us 0.1 tokens.
uint256 _totalTokens = _ethereumSent / _tokenPrice;

// So this returns 0, but we want 1e17 because of the fact that our token has 18 decimals.
return _totalTokens;
}

How do I get the desired results? Thanks in advance, I'm more then willing to provide any additional information.

I believe what you are trying to achieve can be done by including the actual decimal places to _ethereumSent.

Replace _totalTokens with this:

uint256 _totalTokens = (_ethereumSent * 10**18) / _tokenPrice;

or this if you prefer scientific notation:

uint256 _totalTokens = (_ethereumSent * 1e18) / _tokenPrice;

1e18 or 10**18 represents the number of decimals to your token.

You should get the right answer for each scenario and the right amount of tokens based on the decimal value.

The overall theme when it comes to doing math in solidity is...always multiply the numerator by the squared amount of precision needed and account for that in your code.