2

Plutus provides arithmetic functions for Integers through the modules PlutusTx.Prelude and PlutusTx.Builtins. Are there floating-point arithmetic functions which can be used on chain? If not, why is it so?

3 Answers 3

1

My opinion would be that:

Floating point operations are typically resource-consuming and expensive to compute.

I mean, even 1 ADA had to be made a million Lovelace in order for the possibility to have fractional amount of ADA.

I'd suggest you follow the same approach

  • Let the onchain code deal with Integer and carry-out floating point operations off-chain.
1

I used before this for operate with some divisions between Integers and then to truncate to closes integer again.

https://playground.plutus.iohkdev.io/doc/haddock/plutus-tx/html/PlutusTx-Ratio.html#t:Rational

Like this:

number1 = 10  
number2 = 3  
result = TxRatio.truncate ( TxRatio.unsafeRatio number1 number2)   

I think its just too expensive to operate with them on chain, ill not recommend, but you can if you need it.

0

Floats are well known to be the wrong datatype for encoding anything resembling money, fixed points should be used for such purposes.

Encoding them by Integer (with some hardcoded number of fractional decimals) is prone to errors by mistake, so you better wrap it into custom newtype. That is actually what Plutus Lovelace datatype does.

I am not aware of implementation for full-featured Decimal datatype in Plutus, but they are usually can be avoided in smart-contract logic.

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.