Fixed Point Arithmetic

in progress

Computers are imprecise with large numbers. Indeed, floating point arithmetic is not used in the runtime because it can introduce nondeterministic calculations.

Permill, Perbill, Fixed64...

Checking for Overflows/Underflows

We can use the checked traits in substrate-primitives to protect against overflow/underflow when incrementing/decrementing objects in our runtime. To follow the Substrat collectable tutorial example, use checked_add() to safely handle the possibility of overflow when incremementing a global counter. Note that this check is similar to SafeMath in Solidity.


# #![allow(unused_variables)]
#fn main() {
use runtime_primitives::traits::CheckedAdd;

let all_people_count = Self::num_of_people();

let new_all_people_count = all_people_count.checked_add(1).ok_or("Overflow adding a new person")?;
#}

ok_or() transforms an Option from Some(value) to Ok(value) or None to Err(error). The ? operator facilitates error propagation. In this case, using ok_or() is the same as writing


# #![allow(unused_variables)]
#fn main() {
let new_all_people_count = match all_people_count.checked_add(1) {
    Some (c) => c,
    None => return Err("Overflow adding a new person"),
};
#}