Pardon the n00b question!

I am trying to do some simple math in solidity using USD values.

For example, say the start price of a token offering is $0.50 USD and the contribution is $10.00 USD, then the number of tokens issued should be 20 tokens.

I am having trouble with the numbers with solidity.

Since Solidity doesn't use decimal places, I was assuming:

$0.50 USD would be represented as 0500000000000000000; //0.500000000000000000

$10.00 USD would be represented as 10000000000000000000; //10.000000000000000000000000

If I lead any unit values with zeros, Remix reports Expected primary expression. as the error.

What's the best way to do math if you need to account for decimal places in Solidity?

I am not looking to way any ETH, WEI math, just USD math accounting for at least 4 decimal places.

Thank you in advance!!!

  • 2
    Just use cents instead of dollars. It is usually a bad idea to use fraction numbers for money. Feb 18, 2020 at 10:32

1 Answer 1


I would do something like this so you don't have to count zeros all day:

function test() public pure returns (uint256) {
    uint256 amount = 10 * 10**18;
    uint256 price = 0.5 * 10**18;

    assert(amount / price == 20);
  • Would this method be at risk of any overflows? Is there an equivalent way using SafeMath.sol?
    – wardsback
    Mar 3, 2018 at 15:47
  • The code I shared can't overflow, because the only numbers in it are literals known at compile-time. In general, 2^256 is about 10^77, so you can safely multiply a number by 10^18 as long as the number never exceeds 10^59. 10^59 is a lot of dollars. :-) If you are accepting untrusted numbers from outside your contract, just require them to be in a reasonable range.
    – user19510
    Mar 3, 2018 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.