github.com/tanqiangyes/govalidator@v0.0.5/numerics.go (about) 1 package govalidator 2 3 import ( 4 "math" 5 6 "golang.org/x/exp/constraints" 7 ) 8 9 // Abs returns absolute value of number 10 func Abs[V constraints.Integer | constraints.Float](value V) V { 11 return V(math.Abs(float64(value))) 12 } 13 14 // Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise 15 func Sign[V constraints.Integer | constraints.Float](value V) float64 { 16 if value > 0 { 17 return 1 18 } else if value < 0 { 19 return -1 20 } 21 return 0 22 } 23 24 // IsNegative returns true if value < 0 25 func IsNegative[V constraints.Integer | constraints.Float](value V) bool { 26 return value < 0 27 } 28 29 // IsPositive returns true if value > 0 30 func IsPositive[V constraints.Integer | constraints.Float](value V) bool { 31 return value > 0 32 } 33 34 // IsNonNegative returns true if value >= 0 35 func IsNonNegative[V constraints.Integer | constraints.Float](value V) bool { 36 return value >= 0 37 } 38 39 // IsNonPositive returns true if value <= 0 40 func IsNonPositive[V constraints.Integer | constraints.Float](value V) bool { 41 return value <= 0 42 } 43 44 // InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string. 45 // All types must the same type. 46 // False if value doesn't lie in range or if it incompatible or not comparable 47 func InRange[V constraints.Ordered](value V, left V, right V) bool { 48 if left > right { 49 left, right = right, left 50 } 51 return value >= left && value <= right 52 } 53 54 // IsWhole returns true if value is whole number 55 func IsWhole[V constraints.Integer | constraints.Float](value V) bool { 56 return math.Remainder(float64(value), 1) == 0 57 } 58 59 // IsNatural returns true if value is natural number (positive and whole) 60 func IsNatural[V constraints.Integer | constraints.Float](value V) bool { 61 return IsWhole(value) && IsPositive(value) 62 }