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

David Sweeris davesweeris at mac.com
Mon Jun 27 17:11:48 CDT 2016


That’s a very good point, IMHO.
- Dave Sweeris
> On Jun 27, 2016, at 2:43 PM, Stephen Canon via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> 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
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list