Failed to divide with custom type

I have a custom type that performs division operations but it outputs a 0


#[derive(Serialize, Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Hash, Default)]

pub struct Nat(pub BigUint);

let  share_amount:Nat= 1_000_000_000
let pool_balance:Nat= 1_200_000_000
let pool_share: Nat =  share_amount / pool_balance;
output= 0

expected output 0.83333333333

Nat is present inside Candid crate

I the name doesn't lie then we are talking about integers. 1_000_000_000 divided by 1_200_000_000 is, indeed, 0 (and remainder is 1_000_000_000).

2 Likes

Could you please edit your post to include the name of the crate you're using (where you got BigUint) so we don't have to search for it?

Addition and subtraction are working fine, but division produce 0

Is there a way to perform calculation from Nat to f64 and after convert to Nat without precision loss?

There are conversion methods in the set of libraries you're using, see:

But precision can always be lost when coercing from a larger number of bits to a smaller number of bits. There is no way to represent the same precision with less bits.

2 Likes

Apart from the precision loss, converting 0.833333 to an integer will still give you either 0 or 1 depending on whether you round or truncate.

A better alternative would be reordering the operations such that you never need to represent non-integer numbers. For example if the division is followed by a multiplication then do the multiplication before the division.

3 Likes

Obviously no, because f64 it only 64bit (as the name implies) but bignum can be of arbitrary size but only integer ones.

There are crates which may work with long floats, too, but I have never used them.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.