How can I calculate a percentage of a number using Parity Ink?

233 Views Asked by At

So my problem is, that I am trying to calculate a percentage for a share, but ink! doesn't support floating points and I have no clue on how I can get a non-floating value that UI will denominate for me later.

For an example, this code will not compile.

let total_amount: u128 = 250;
let share: u128 = 104;
let percentage = (share as f64 /total_amount as f64) * 100 as f64;
// percentage = 41.6

Is there anyway to get a non-floating value for the percentage so I can denominate the returned number to decimals in UI? Or is there any other solutions to my problem?

1

There are 1 best solutions below

1
Paweł Obrok On

Use integer math, but scale your number first:

let total_amount: u128 = 250;
let share: u128 = 104;
let share_percent = share * 100 / total_amount; // 41

or, if you want more decimals:

let share_fraction = share * 10000 / total_amount; // 4160

then format the number appropriatly on the frontend, for example if your contract returns per_10000, like in the second example, then (or use some formatting library of choice more likely):

4160 / 100 + '%' // 41.6%

You might want to look into using checked_mul/checked_div or saturating_mul/saturing_div in your contract code instead of regular * / to make sure you control how your code handles boundary values.