Best way of converting a UInt256 into a UFix64 in Cadence without losing precision

44 views Asked by At

So I'm working on the port of the BandProtocol oracle contract to Cadence.

Their standard way of presenting the rate data is multiplied by e18.

In the cadence version, we want to provide an additional field on the struct that will have the information in fixed point format for easier consumption by other cadence contracts.

I'm wondering if there is a best way of doing that, I believe there will be two potential ways, considering pub let e18: UInt256 = 1000000000000000000:

UFix64(rate/e18) or UFix64(rate)/UFix64(e18)

1

There are 1 answers

0
Deniz Mert Edincik On BEST ANSWER

I came up with this, covers all UFix64 I guess

UFix64(rate / 1_000_000_000_000_000_000) + UFix64((rate/10_000_000_000) % 100_000_000) / 100_000_000.0

https://run.dnz.dev/snippet/4f5342c367eb2db5