# How to calculate token buy and sell prices?

I have a ERC20 token

``````    string public name = "Token ZIZ";
string public symbol = "ZIZ";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000 * 10 ** uint256(decimals);

/// the price of tokenBuy
uint256 public TokenPerETHBuy = 10000;  /// 1 TOKEN = 0.001 ETH

/// the price of tokenSell
uint256 public TokenPerETHSell = 10000;

/**
*  function for Buy Token
*/

function buy() payable public returns (uint amount){
require(msg.value > 0);

amount = ((msg.value.mul(TokenPerETHBuy))).div(1 ether);

balanceOf[this] -= amount;                        // adds the amount to owner's
balanceOf[msg.sender] += amount;
emit BuyToken(msg.sender,msg.value,amount);
return amount;
}

/**
*  function for Sell Token
*/

function sell(uint amount) public returns (uint revenue){

require(balanceOf[msg.sender] >= amount);         // checks if the sender has enough to sell
balanceOf[this] += amount;                        // adds the amount to owner's balance
balanceOf[msg.sender] -= amount;                  // subtracts the amount from seller's balance

revenue = (amount).div(TokenPerETHSell) ;

msg.sender.transfer(revenue);                     // sends ether to the seller: it's important to do this last to prevent recursion attacks
emit Transfer(msg.sender, this, amount);               // executes an event reflecting on the change
return revenue;                                   // ends function and returns

}
``````

How can I achive my result ? 1 TOKEN = 0.001 ETH.

## 1 Answer

From your comments `TokenPerETHBuy` should be 1000 instead, also `TokenPerETHSell` should be 1000.

In the `buy` function the amount is calculated without taking into account token `decimals`. It should be:

``````amount = msg.value.mul(TokenPerETHBuy);
``````

Because you have `decimals = 18`. For `1 ether = 10^18 wei` you have to receive `1000 * 10^18` tokens.