2

I want to check, if the first digit of a uint256 is equal 5.

I therefore do the following:

function _numDigits(uint256 _number) internal pure returns (uint8) {
  uint256 number = _number;
  uint8 digits = 0;
  while (number != 0) {
      number /= 10;
      digits++;
  }
  return digits;
}

function firstDigitIsFive(uint256 _number) external pure returns (bool) {
    uint256 numdigits = _numDigits(_number);
    if(numdigits == 1) {
        return _number == 5;
    } else {
        return _number/10**(numdigits-1) == 5;
    }
}

Is there a better, easier and cheaper way to evaluate the first digit of an uint256?

0
2

Substitute x for whichever number you want to check for.

function highestOrderDigitIsX(uint256 number, uint256 x) public pure returns (bool) { 
    while (number >= 10) {
        number /= 10;
    }
    
    return number == x;
}

For completeness:

function lowestOrderDigitIsX(uint256 number, uint256 x) public pure returns (bool) {
    return number % 10 == x;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.