[Ethereum] Ethereum tokens and decimals

go-ethereummetamasksoliditytokensweb3js

What is the best way to deal with decimals as I create a currency?

Let's use an example. I have KARLCOIN (KARL), and I have 1,000,000 of them, and the token has 6 decimals places. This token will also have a crowdfund where 100 KARL = 1 ETH ( 0.01 ETH / KARL).

When I create this contract, I should do something like:

// Constructor
 function token() {
    owner = msg.sender;
   totalSupply = 1000000;
  balances[owner] = totalSupply;
  decimals = 6;
  symbol = "KARL";
  }    

And then that token also has a function to transfer.

Now, how am I calculating, transferring, and displaying these amounts?
For instance, 1,000,000 KARL is 1,000,000,000,000 of the smallest unit of my coin. Let's call it microKarl, or mk.

Does that mean the totalSupply in my constructor should actually be 1,000,000,000,000? When I transfer amounts to people, am I transferring it in mK? Basically the the amount of Karl * 1,000,000 to get it in to it's microKarl form? How will MyEtherWallet and MetMask and such know how to display the correct amount?

If I was using web3 to display it, I could just do the math and display it myself. Get the amount in mK, times it by 0.000001, and then be on my way. Right? Or am I off track here?

I made a token and did something like this (it's been a long night) and sent myself the tokens and in MetaMask it says the correct amount. On Etherscan it does not, it shows a much smaller amount, and also says the decimals are "18" when MetaMask grabbed them as 6 just by pasting the contract address in.

I'm just a bit confused on the decimalization of tokens and feel like I don't have the foundation of what I'm doing to debug this. Any clarity would be appreciated.

Best Answer

If your token follows ERC20 standard (and it should if you want it to be handled by wallets or client applications) you can include (it is not mandatory but handled by most clients) decimals information.

So your contract should contain something like:

uint8 public constant decimals = 6;

And your code should assume the amounts are in the smallest possible units.

Related Topic