Double to String conversion implementation

Looking at the docs for Strings, String | Apple Developer Documentation, i could not find the initializer that takes a double to convert. I wanted to know if the doc is missing an api, because I know there is one..

I’m looking to learn how the conversion is implemented. particularly, what happens if the input double is really long like 0.49999999... For example, in java it returns a string of a value with the fewest decimal places that can convert back to the given double, so possibly 0.45.

To understand how Swift converts types to String you should read up on the initializers under String.init(describing:)

This means that you should investigate each protocol conformance which has a supported initializer via this group.

The relevant initializer is this one, unless I'm mistaken and there's another more specific:

The documentation doesn't have any information specific to floating-point values. However, conformance to LosslessStringConvertible (as all of the standard library floating-point types do) provides an important guarantee that you touch on: the string representation you get has enough information that it can be converted back to exactly the same floating-point value you start out with.

How exactly it's done is an implementation detail which can change at any time. However, since Swift 4.2, the standard library has used a variation of the Grisu2 algorithm with changes described in Errol3, which means that you'll get a string representation with the minimum number of digits required for lossless conversion and with good performance (but, again, the API makes no such guarantee):

The implementation was recently re-written in native Swift, partly to support Embedded use cases:

3 Likes