Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in Ethereum Solidity

I am creating a contract that issues tokens. I would like an account that holds tokens to be able to check what percentage they own out of all the tokens issued. I know that Ethereum has not implemented floating point numbers yet. What should I do?

like image 254
GK1 Avatar asked Mar 11 '17 17:03

GK1


People also ask

What is decimal in Solidity?

To solve this issue, all tokens on Ethereum/Binance Chain consider some big decimal number as a threshold of double and ceil parts. In ERC20 tokens this number is calculated based on the decimal field of the contract: 10^decimal . For the native token ETH/BNB, there is a fixed decimal equal to 18.

Is Ethereum written in Solidity?

Solidity is the primary language on Ethereum as well as on other private blockchains, such as the enterprise-oriented Hyperledger Fabric blockchain.

Can a smart contract have multiple constructors?

A contract can have only one constructor. A constructor code is executed once when a contract is created and it is used to initialize contract state. After a constructor code executed, the final code is deployed to blockchain.


1 Answers

It's probably best (lowest gas cost and trivial to implement) to perform that calculation on the client rather than in Solidity.

If you find you need it in Solidity, then it's just a matter of working with integers by shifting the decimal point. Similar to: https://en.wikipedia.org/wiki/Parts-per_notation

For example, this function let's you decide the degree of precision and uses one extra degree of precision to correctly round up:

pragma solidity ^0.4.6;

contract Divide {

  function percent(uint numerator, uint denominator, uint precision) public 

  constant returns(uint quotient) {

         // caution, check safe-to-multiply here
        uint _numerator  = numerator * 10 ** (precision+1);
        // with rounding of last digit
        uint _quotient =  ((_numerator / denominator) + 5) / 10;
        return ( _quotient);
  }

}

If you feed it 101,450, 3 you get 224, i.e. 22.4%.

Hope it helps.

like image 191
Rob Hitchens Avatar answered Oct 16 '22 16:10

Rob Hitchens