[Ethereum] How to store a float or decimal in a contract?


I want to store the purchase price of a digital asset within the contract and then allow a user to purchase it. I have the following struct with some demo hard coded values but using a uint for the purchasePrice field isn't working

Asset memory _asset = Land({
                geoPoint1: 'ldsfsdfsdf',
                geoPoint2: 'ldsfsdfsdf',
                geoPoint3: 'ldsfsdfsdf',
                geoPoint4: 'ldsfsdfsdf',
                creationTime: uint64(now),
                itemdemo: 100000,
                purchasePrice: 1.20

Best Answer

Deep down, everything is uint.

In practice, what this means is you should establish the minimum unit and maximum divisibility your app supports. For example, a "dollar" (generally) has two decimals (penny) and no further division is (generally) possible.

Suppose you want up to 4 decimal places. Use integers raised by 10**4. It is a best practice to externalize this concern from the contract. That is, leave it to clients to convert contract style numbers to human-readable notation.

purchasePrice: 12000 // using 4 decimal places consistently

The ERC20 token standard and ethereum itself both use fixed decimal places and integer math internally, relying on clients to convert to human-readable notation. ERC20 leaves the decision about the number of decimals to the developer. That global parameter signals wallets and exchanges so they can know how to present the integer values.

Hope it helps.

Related Topic