14

Where can I find the maximum and minimum values that various types can store? And an epsilon value for floats?

I'm looking for something like C's limits.h, but for Solidity / EVM.

2 Answers 2

13

Updated 2020

Solidity 0.6.8 introduced min and max keywords that can now natively tell you the min and max of an expected type. From the release page:

Implemented type(T).min and type(T).max for every integer type T that returns the smallest and largest value representable by the type.

You can try it out with the following code. Note that the uint256 values can be swapped for any valid integer type:

pragma solidity ^0.6.8;

contract TestContract {
    uint256 public a;
    uint256 public b;
    
    function myTest() external {
        a = type(uint256).min;
        b = type(uint256).max;
    }
}
19

I assume you mean the integer types, because those are really the only types in Solidity that have a maximum and a minimum.

Solidity does not support floating point types, and most likely will never because they are considered not to be precise enough. Ethereum contracts need to be 100% deterministic, and always run the same way on all hardware.

Solidity will in the future support fixed-point types, but it doesn't yet.

Firstly, int means int256 and uint means uint256. Once you know the amount of bits your integer has, you can easily calculate the minimum and maximum using bitwise arithmetic:

int256 constant INT256_MIN = int256(uint256(1) << 255);
int256 constant INT256_MAX = int256(~(uint256(1) << 255));
uint256 constant UINT256_MIN = 0;
uint256 constant UINT256_MAX = ~uint256(0);

All the bitwise shifting is done on unsigned ints to avoid any special behaviour on the sign bit.

3
  • Cheers! FYI, standard like IEEE754 would run deterministically on all hardware. Regardless, there is a virtual machine abstraction layer.
    – Tom Hale
    Commented Oct 5, 2017 at 8:35
  • @TomHale Yeah, a standard is a standard ofcourse. Thing is, I've had problems with 64-bit float arithmetic being compiled to extended precision 80-bit float arithmetic without anyone noticing. After the calculations were done, the compiler converted the 80-bit float back to 64-bit float. This caused apparent differences on different hardware, which was kind of a disaster. Ofcourse it was the compiler's and the programmers' fault, not the hardware's or the standard's. I guess I'm a bit prejudiced against floats :-)
    – Jesbus
    Commented Oct 5, 2017 at 8:46
  • Fixed point and rational numbers do exist!
    – Tom Hale
    Commented Oct 5, 2017 at 12:05

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.