3

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!

1 Answer 1

1

Note that FixedU128 is not a floating point type. It represents floating point numbers using u128 type with 18 digits of precision. This means that the last 18 digits of any number are taken to be the fractional part and the rest are taken to be the integer part.

This way, we can represent 1.23 as 1_230_000_000_000_000_000. Where 230_000_000_000_000_000 is the fractional part and 1 is the integer part.

So 500000000000000000 is the correct value. You can see that by printing it using the debug format

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

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.