Skip to content

Instantly share code, notes, and snippets.

@2075
Last active March 2, 2022 14:15
Show Gist options
  • Save 2075/f82f1ac087a1436e730abaf0c3b7b772 to your computer and use it in GitHub Desktop.
Save 2075/f82f1ac087a1436e730abaf0c3b7b772 to your computer and use it in GitHub Desktop.
Substrate and Fixed Point Arithmetic

Collection of reference material to do fixed point arithmetic on substrate based chains.

overview

How can I do math on floating point values in substrate runtime. As a simple example imagine I want to keep track of an interest rate in a decentralized finance application. I can prototype by using the percentage as an integer:

  let rate = 2;
  let dividend = capital * rate / 100;

But what if my interest rate is 2.5% or 2.4554%? Is there any standard way to do floating point arithmetic?

Since Substrate is a framework for blockchains, it is important that each node arrives at the same deterministic result for consensus. Floating point arithmetic is not deterministic and so for this reason is not allowed in Substrate. The standard way of handling arithmetic where you will need decimal places is to use one of the in-built primitive types for handling fixed point arithmetic. Fixed point arithmetic is safe for Substrate since it represents all rationals as a fraction and always resolves to a deterministic result. The two types which are used to handle fixed point arithmetic are the Permill and the Perbill types.

examples

links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment