"Real" scientific notation with string interpolation

Hello,

I was getting ready for a "What's new in Swift 5" meetup presentation and noodling around with string interpolation. Inspired by Michael Ilseman and Zipper's recent try! Swift talk ( https://youtu.be/lMhGnTFA9CI ), I thought I would post my code to see if you had any feedback for me. :slight_smile: Also, a couple of questions below.

I am guessing that I am reinventing some of the fundamentals that will be implemented in future Swift in a much better way.

I wanted to be able to take a number like 6.02e23 and show it in the form 6.02x10^23 (except using unicode superscript numbers). My first version used String(format:) and then split based on the "e". This is considered bad form now, right?

I had some trouble with log10 and BinaryFloatingPoint and the escape hatch I used was converting to a Double(). Any better ideas?

It seems like there should be an easy way to take an array of Characters and join it to a String. I couldn't figure out how to do that so, I just converted to an array of Strings and joined.

I started out with one interpolation but then broke it up into three. One for the scientific notation, one for superscript numbers, and one for enforcing precision. I am loving the interpolation design because it feels very composable. It will be great once we have a bunch of batteries-included, fundamental building in the standard library.

Here is a link to my code:

Thank you. Best wishes,
Ray

@scanon could probably show you how to get the information you want out of a BinaryFloatingPoint.

You can use String's generic initializer: String(myCharArray), so your code would be (where toSuper is [Character : Character])

    mutating func appendInterpolation(superscript value: Int) {
        let string = String(value)
        let result = String(string.map {
            String.StringInterpolation.toSuper[$0]!
        })

        appendInterpolation(result)
    }
2 Likes

Binary-to-decimal conversion is hard to do right, and the difficulties go way beyond log10; your best easy option today is actually probably to use String(value) and then disassemble and reformat the resulting string. The String initializer has a very fast and high-quality conversion to decimal.

If you want to learn more about how to do it more generally, the implementation of the String initializer is a good place to start.

2 Likes