Module polkadot_sdk_frame::arithmetic::per_things
Expand description
Types that implement PerThing
can be used as a floating-point alternative for
numbers that operate within the realm of [0, 1]
. The primary types may you encounter in
Substrate would be the following:
In use, you may see them being used as follows:
Perbill
, parts of a billion
#[test]
fn perbill_example() {
let p = Perbill::from_percent(80);
// 800000000 bil, or a representative of 0.800000000.
// Precision is in the billions place.
assert_eq!(p.deconstruct(), 800000000);
}
Percent
, parts of a hundred
#[test]
fn percent_example() {
let percent = Percent::from_rational(190u32, 400u32);
assert_eq!(percent.deconstruct(), 47);
}
Note that Percent
is represented as a rounded down, fixed point
number (see the example above). Unlike primitive types, types that implement
PerThing
will also not overflow, and are therefore safe to use.
They adopt the same behavior that a saturated calculation would provide, meaning that if one is
to go over “100%”, it wouldn’t overflow, but simply stop at the upper or lower bound.
For use cases which require precision beyond the range of [0, 1]
, there are fixed-point types
which can be used.
Each of these can be used to construct and represent ratios within our runtime.
You will find types like Perbill
being used often in pallet
development. pallet_referenda
is a good example of a pallet which makes good use of fixed
point arithmetic, as it relies on representing various curves and thresholds relating to
governance.
§Fixed Point Arithmetic with PerThing
As stated, one can also perform mathematics using these types directly. For example, finding the percentage of a particular item:
#[test]
fn percent_mult() {
let percent = Percent::from_rational(5u32, 100u32); // aka, 5%
let five_percent_of_100 = percent * 100u32; // 5% of 100 is 5.
assert_eq!(five_percent_of_100, 5)
}
Structs§
- A fixed point representation of a number in the range [0, 1].
- A fixed point representation of a number in the range [0, 1].
- A fixed point representation of a number in the range [0, 1].
- A fixed point representation of a number in the range [0, 1].
- A fixed point representation of a number in the range [0, 1].
Enums§
- The rounding method to use for unsigned quantities.
- The rounding method to use.
Traits§
- Something that implements a fixed point ration with an arbitrary granularity
X
, as parts perX
.
Type Aliases§
- Get the inner type of a
PerThing
. - Get the upper type of a
PerThing
.