[swift-evolution] [Proposal] Add floor() and ceiling() functions to FloatingPoint

Stephen Canon scanon at apple.com
Mon Jun 27 14:43:57 CDT 2016


> On Jun 27, 2016, at 3:34 PM, Saagar Jha <saagarjha28 at gmail.com> wrote:
> 
> Seems fine to me. One addition though: some sort of round(withPrecision: Int)

I noted in another post on this thread that this doesn’t actually make any sense for FloatingPoint.  I’ll flesh that out here for everyone’s benefit.

When people talk about rounding to some precision, they almost universally mean “some number of decimal digits”.  But for binary floating-point types, rounding to any number of decimal digits other than zero doesn’t actually work.  E.g.:

	(1.15).round(withPrecision: 1) // returns 1.1

Why do we get 1.1 here instead of the expected 1.2?  Because 1.15 is actually 1.149999999999999911182158029987476766109466552734375.  For that matter, we haven’t actually succeeded in rounding to one decimal digit; the resulting value isn’t actually 1.1, but rather 1.100000000000000088817841970012523233890533447265625.

For binary floating-point types, the correct way to make rounding to a fixed number of digits behave as expected is to do it *at the point that the value is converted to a String for display, as part of the formatting*, never as a separate operation.

For a hypothetical DecimalFloatingPoint protocol, on the other hand, it would be perfectly reasonable to have the proposed operation:

	func rounded(digits: Int = 0, rule: RoundingRule) -> Self

– Steve


More information about the swift-evolution mailing list