Photo by Chris Liverani on Unsplash

Dealing With Decimals In Smart Contracts

--

In cryptography, we often use unsigned integers, and never have much to do within floating-point values. But, obviously, we need floating-point values for many of our calculations, such as for calculating compound interest in a financial contract or computing the area of a circle. And, so, if we need to implement decimal operations in our smart contracts, we need the addition of code that processes decimal values but uses integer operations.

The basics of decimal operations

So let’s see how we can perform maths operating using decimal values. For example, some simple calculations are:

6.1 + 5.2 = 11.3
6.1 * 5.2 = 31.72
6.1 - 5.2 = 0.9
6.1 / 5.2 = 1.173
1/6.1 = 0.1639

One method of supporting decimals is basically to move the decimal point so that the value looks like an integer. For example, 6.546 could be 6546 and 3.134 could be 3134, and where we move three decimal places. As long as we remember how many places we move the decimal point, we can reverse the operations. And so adding is easy:

6546 + 3134 = 9679

and, as we have shifted by three decimal places we get 9.679. When we multiply we get:

6546 *3134 = 20512030

--

--

Prof Bill Buchanan OBE FRSE
ASecuritySite: When Bob Met Alice

Professor of Cryptography. Serial innovator. Believer in fairness, justice & freedom. Based in Edinburgh. Old World Breaker. New World Creator. Building trust.