#4 Dealing with fractions in Solidity -Smart contract

Fixed point numbers is not fully supported in solidity , but the fixed point numbers or fractions are used frequently in contract. For instance when writing a ERC20 Token,you would value 1 token to 0.5 ether and you may have to value token based upon ether paid to the contract as well return excess ethers in fractions.  In such cases converting all of your units to “wei(1 ether =1,000,000,000,000,000,000 wei)” ,would ease arithmetic operations .

Problem :

Assume a case where we want to have a payable function that accepts 0.5 ether or more and all ethers less than 0.5 should get reverted.

Note :  ufixed can only be declared and it cannot be either returned or assigned in  contract, its not an ideal solution for the problem.

Solution :

If you use uint types,you would land no where as decimals would be truncated , Instead we can use wei (denomination of ether  – 1 ether =1,000,000,000,000,000,000 wei).  All of the ethers supplied to the contract defaults to wei, we could take advantage of this and represent our value of token condition in wei as below

var reqfraction= (1 ether * minvaltoken) / mintokendenomination;


pragma solidity ^0.4.18;
contract Sample {
uint256 public minvaltoken =5;
uint256 public mintokendenomination =10;
function() payable {
var value= (msg.value);
var reqfraction= (1 ether * minvaltoken) / mintokendenomination;
if(value < reqfraction) {

view raw
hosted with ❤ by GitHub










Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s