DEV Community

Loading Blocks
Loading Blocks

Posted on

Solidity arithmetic and type conversion

Integer Division

Solidity does not support floating-point arithmetic.

Integer division in Solidity truncates the decimal part.

for example: 10 / 7 = 1

different integer type arithmetic

Different integer types(uint and int) cannot be used in arithmetic directly.

Smaller-bit integers are implicitly converted to larger-bit integers when different bit and same type(uint8 and uint256) integer calculating

type conversion

Explicit conversion is required when implicit conversion is not possible.

The constructor syntax type is used for type casting.

For example: uint(myIntVariable) make ** myIntVariable** converted to uint type。

conversion risk

  1. casting from larger to smaller types may cause overflow.

  2. converting a negative signed integer to an unsigned integer will revert the transaction.

Best Practices

1.It is safer to cast smaller types to larger types, can avoid dataloss or runtime errors.
2.always check value ranges before down-casting.

Top comments (0)