How to use FixedU128?

98 views Asked by At

I'm fetching floating value in offchain worker though lite-json.

Json data:

{
"price": 0.5
}

Here is the implementation to fetch the price:

let price_str = match obj.clone() {
    JsonValue::Object(obj_data) => {
        let (_, v) = obj_data
            .into_iter()
            .find(|(k, _)| k.iter().copied().eq("price".chars()))?;
        match v {
            JsonValue::Number(val) => val,
            _ => return None,
        }
    }
    _ => return None,
};
let bits = price_str.integer as u128 * 10u128.pow(price_str.exponent as u32)
    + u128::from(price_str.fraction);
log::info!("bits: {}", bits);
// Adjust the denominator based on the desired scale
let fixed_value =
    FixedU128::saturating_from_rational(bits, 10u128.pow(price_str.fraction_length as u32));

log::info!("value of integer is {}", fixed_value);

I'm getting these logs:

2023-12-09 22:25:03.084  INFO      offchain-worker pallet_template: bits: 5    
2023-12-09 22:25:03.084  INFO      offchain-worker pallet_template: value of integer is 500000000000000000

I should get fixed_value to be 0.5 but getting 500000000000000000.

I have tried almost all the methods to convert this but either i get 0 or 500000000000000000.

How to fetch this price effectively?

Thanks in advance!

I have tried other options also instead of saturating_from_rational to convert this but either i get 0 or 500000000000000000.

0

There are 0 answers