diff --git a/src/core/CCFloat.ml b/src/core/CCFloat.ml index 2fbbe071..0d73342d 100644 --- a/src/core/CCFloat.ml +++ b/src/core/CCFloat.ml @@ -60,6 +60,17 @@ let sign_exn (a:float) = if is_nan a then raise (TrapNaN "sign_exn") else compare a 0. +let round x = + let low = floor x in + let high = ceil x in + if x-.low > high-.x then high else low + +(*$= + 2. (round 1.6) + 1. (round 1.4) + 0. (round 0.) +*) + let to_int (a:float) = Pervasives.int_of_float a let of_int (a:int) = Pervasives.float_of_int a diff --git a/src/core/CCFloat.mli b/src/core/CCFloat.mli index a2e423f2..538d2068 100644 --- a/src/core/CCFloat.mli +++ b/src/core/CCFloat.mli @@ -58,6 +58,10 @@ val fsign : t -> t (** [fsign x] is one of [-1., -0., +0., +1.], or [nan] if [x] is NaN. @since 0.7 *) +val round : t -> t +(** [round f] returns the closest integer value, either above or below + @since NEXT_RELEASE *) + exception TrapNaN of string val sign_exn : t -> int (** [sign_exn x] will return the sign of [x] as [1, 0] or [-1], or raise an