[swift-users] Decimal to Double?

Joe Groff jgroff at apple.com
Mon Nov 28 13:21:25 CST 2016


> On Nov 28, 2016, at 9:22 AM, Alex Blewitt via swift-users <swift-users at swift.org> wrote:
> 
> NSDecimal conforms to the ExpressibleBy(Float|Integer)Literal, but that just means it can be created from a literal value, not the other way around:
> 
> https://github.com/apple/swift-corelibs-foundation/blob/108a5b0006912c6cf6b59e4954255237bf01b67a/Foundation/NSDecimal.swift#L319-L329
> 
> 
> 
> extension Decimal : ExpressibleByFloatLiteral {
>     public init(floatLiteral value: Double) {
>         self.init(value)
>     }
> }
> 
> extension Decimal : ExpressibleByIntegerLiteral {
>     public init(integerLiteral value: Int) {
>         self.init(value)
>     }
> }

It really shouldn't be, since ExpressibleByFloatLiteral uses a binary float initial value and so doesn't guarantee decimal accuracy. I'd recommend using init(mantissa:exponent:isNegative:) instead, and minimizing any conversions between Double and Decimal.

-Joe


More information about the swift-users mailing list