Ethereum vyper tutorial: Understanding //
Syntax
As a programmer who uses a VYPER for the development of a smart contract, you can find the following error when performing department operations:
`
Incorrect municipality: cannot execute decimal division at NIint256
This question is because Vyper does not support decimal arithmetic. When shared by twonint256numbers in VYPER 0.4.0b or later, it throws an exception and an invalid of thepoperation
.
What is the difference between //
i (convert)?
In Vyper there are two syntax to perform conversions:
-
// Convert ()
:
– This method restores the converted value.
– One argument is required to turn) and return the new nint256
.
– When used with division operator (/
) or modulo operator (%
), it can cause problems due to the imprecision of numbers with a movable point.
-
(convert (price, nint256))*...
:
– This method takes two arguments: value (as a string) and an unsigned integer.
– He tries to turn a string into a nint256
, then multiplies it with a given number.
– In Vyper 0.4.0b or later, this syntax is recommended for decimal division.
How to solve the problem
To correct the error when performing a division into vyper:
- Turn your values using
(convert (price, nint256))*...
When you share two nint256
numbers, use the upper syntax:
`V.
DIV (result, 10); // on the assumption that the “result” is a variable that holds one of the numbers
`
- Avoid using// Convert ()
in decimal division
As mentioned earlier, Vyper does not support decimal arithmetic when using the//method. Instead, use
(convert (price, nint256)) * ….
Example uses the case: decimal division
To demonstrate this approach, let's create a simple example:
V.
MATHEMATIC CONTRACT
Function to divide (A: U32, B: U8) Public Clean Returns (U32) {{
Return (a / convert (b, u256)) % 10; // Using a converted value for decimal division
Iche
Iche
`
In this clip of the code:
-Convert (1, 2)is a conversion function that turns a string into a
nint256.
The converted method can handle IU32
and 8, which makes it suitable for our example.
- in the function ofdivide,(convert (b, U256))
provides decimal arithmetic by the conversion of any potential fractional part of ‘b.
– Then we perform the division using the converted value: a / (convert (b, u256)) % 10
.
Conclusion
In this article, we have explored why Vyper throws an exception to invalid formwork" when performing decimal divisions. Understanding how to properly convert values and use the recommended syntax
(convert (price, nint256)) *`, developers can solve this question in their smart contracts based on Vyper.