Is there a similar function in solidity itself or some other popular library such as SafeMath?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.Sign up to join this community
It's a bit funny that the Solidity documentation hints about such a function
abs (https://solidity.readthedocs.io/en/v0.5.3/types.html) but I can't get it to compile at least in Remix. So I assume there is no such function and the documentation is just a bit off (wouldn't be the first time).
There are probably some libraries which contain that functionality but no idea which and where.
Anyway, it's easy to enough to implement it yourself - you gave the formula already :)
Note that you can't just cast
uint and be done with it - it's not allowed. And even if it was, -1 should probably cast into Max(uint) - 1.