Proposal: Add integral rounding functions to FloatingPoint · GitHub
Karl, thanks for writing this up. It should be extended to include not only floor( ) and ceiling( ), but also:
/// Returns the integral value closest to `self` whose magnitude is not greater than that of `self`.
func truncate( ) -> Self
/// Returns the integral value closest to `self`. If two integrers are equally close, the even one
/// is returned.
// NOTE: The name of this function requires bike-shedding. I’ve chosen a deliberately poor
// name as a straw-man.
func roundToNearestTiesToEven( ) -> Self
/// Returns the integral value closest to `self`. If two integrers are equally close, the one with
/// greater magnitude is returned.
// NOTE: The name of this function requires bike-shedding. I’ve chosen a deliberately poor
// name as a straw-man.
func roundToNearestTiesAway( ) -> Self
and mutating versions of those.
Some collected responses to other comments on this thread:
David Sweeris wrote:
The only thing I'm worried about is the situation where we have "x = N.M", and `x.ceiling` equals maybe "(N+2).0" instead of "(N+1).0" because we ran out of precision and can't represent (N+1).0. I'm not sure what the exact values are where floats (or doubles) stop having enough precision to represent inter-integer values... It might be a moot point.
This never happens. Floor and ceiling are always exact operations.
Austin Rathe wrote:
func roundedUp(withPrecision:Int) -> Self { … }
While I understand where you’re going with this, you can’t round non-decimal floating-point numbers to a non-zero number of decimal digits (the result won’t be representable, in general). This should be available for decimal floating-point types if/when they are added, but should be handled as part of conversions to String for binary floating-point types.
– Steve
···
On Jun 25, 2016, at 05:06, Karl via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote: