4

I'm trying to calculate a value of token by using division operator, it will return a number higher then 1, but never returns here is the code of the price calculation:

        #[ink(message)]
        pub fn get_price_for_token_a_as_input(&self) -> Balance {

            let pool_b_amount: Balance = self.token_b.balance_of(self.get_account_id());
           

            let opr:Balance = 10;
            let one = 1*opr.pow(12);


            let price_from_one_token_a_to_b = one (1) / pool_b_amount (200);
            
            

            price_from_one_token_a_to_b
        }

The Value of price_from_one_token_a_to_b is always 0.

the values are already 10^12.

Thanks in advance.

7
  • What is the value of pool_b_amount? What is the expected number you want to get given that value?
    – Shawn Tabrizi
    Mar 9, 2022 at 20:02
  • @ShawnTabrizi Hey, i updated the question, thank you for your time sir. Mar 9, 2022 at 20:14
  • 3
    You should try printing the balance of pool_b_amount to make sure it is 200 and not 200e12.
    – forgetso
    Mar 9, 2022 at 21:48
  • 1
    Yes, I agree with @forgetso.
    – Shawn Tabrizi
    Mar 9, 2022 at 23:17
  • 1
    @forgetso is correct. Mar 18, 2022 at 21:02

1 Answer 1

7

You cannot use floating point maths in ink!. If you do something like 10/7 then you will get 1 as a result (rounded from 1.42857142857).

It looks like you're calculating 1e12/200e12 which is 0.005 and therefore rounded to 0. 1e12/200 is 5e9 and is perhaps what you expected based on your code comments.

Check out this answer for a more complete explanation of why floating point maths is excluded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.