A function which returns the absolute value of a signed value (#2984)
* Add a function which returns the absolute (and obviously unsigned) value of a signed value. * add changelog entry and fix lint Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
This commit is contained in:
@ -40,4 +40,14 @@ library Math {
|
||||
// (a + b - 1) / b can overflow on addition, so we distribute.
|
||||
return a / b + (a % b == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the absolute unsigned value of a signed value.
|
||||
*/
|
||||
function abs(int256 n) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
// must be unchecked in order to support `n = type(int256).min`
|
||||
return uint256(n >= 0 ? n : -n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user