Solidity – Available Fixed and Floating Point Math Libraries

floating-pointsolidity

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?

Best Answer

Disclaimer: I am the author of PRBMath.

Fixed-Point

  1. PRBMath
    • signed and unsigned denary numbers with 18 decimals of precisions
    • offers advanced math functions (logs, exp, pow, etc.)
    • bakes in overflow-safe multiplication and division
    • ultra gas efficient
  2. ABDKMath64x64
    • binary numbers with 2^64 precision
    • offers advanced math functions (logs, exp, pow, etc.)
    • ultra gas efficient (see this praise)
  3. Fixidity
    • denary numbers with arbitrary number of decimals
    • offers advanced math functions (logs, exp, pow, etc.)
    • slower than 64.64, but with a more palatable API
    • used by CementDAO, PoolTogether and Celo
  4. Exponential
    • denary numbers with 18 decimals of precision
    • minimal features, doesn't offer advanced math functions
    • developed by Compound.Finance
  5. DecimalMath
    • denary numbers with 27 decimals of precision
    • minimal features, doesn't offer advanced math functions
    • uses ABIEncoderV2 (experimental in Solidity 0.7 and below)
  6. DSMath
    • denary numbers with 18 (WAD) and 27 decimals of precision (RAY)
    • minimal features, doesn't offer advanced math functions
    • developed by the DappHub team, used by the Maker protocol

Floating-Point

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

Addenda

  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 fantastic resource to learn about how advanced math functions can be implemented in Solidity v0.6 and lower
  3. There are more math libraries mentioned in this OpenZeppelin forum post
Related Topic