5

Solidity doesn't have float or double variables. What solutions are there to handle the cases where we really have to represent numbers as percentages or fractions?

6

Fixed-Point

  1. ABDK Math 64.64
    • binary scalar with 2^64 precision
    • one of the more popular fixed-point libraries, it's been praised as being super efficient
  2. Exponential
  3. Fixidity
    • decimal scalar with arbitrary number of decimals
    • slower than 64.64, but with a somewhat more palatable API
  4. DecimalMath
    • decimal scalar with 27 decimals, the number used by MakerDAO
    • relies on the experimental ABIEncoderV2
  5. DsMath
    • developed by the DappHub team

Floating-Point

  1. ABDK Quad
    • developed by the same company as 64.64
  2. Bankex
    • IEEE-754 octuple precision floating-point

Addenda

The libraries shipped by ABKD and Compound come with no license[1, 2], so you may want to ask for permission before using them.

FWIW:

  1. There's an open issue in the solidity repo for adding native support for fixed-point types
  2. Mikhail Vladimirov's Math in Solidity blog series is a phenomenal resource to better understand how non-trivial math can be implemented in Solidity v0.6 and lower
| improve this answer | |
  • You forgot the simplest (and most accurate) method: maintain a tuple of numerator and denominator, and in every computation, avoid division for as long as possible (i.e., use it only in order to avoid an overflow). – goodvibration May 27 at 20:32
  • That's true, but I'd argue that the simplest approach to fixed-point math in solidity is also the brittlest. – Paul Razvan Berg May 27 at 20:39
  • I had to google-translate brittlest, which gave me: having hardness and rigidity but little tensile strength. Now I have to google-translate pretty much every one of the words in that... – goodvibration May 27 at 20:52
  • Hah, what I meant is, I wouldn't encourage a simple approach when dealing with fixed-points. There's always something that could go wrong, and I'd rather rely on other more robust contracts (and tests!) that people wrote before me. – Paul Razvan Berg May 27 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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