Search code examples
swiftstringformatnumbersdouble

Convert Double to String with minimum fraction digits without using NumberFormatter


Given these Doubles:

let one: Double = 1
let alsoOne: Double = 1.0
let oneAsWell: Double = 1.00
let x: Double = 1.10
let y: Double = 1.010
let z: Double = 1.0010

How can I convert them to String so they keep only their relevant fraction digits without a NumberFormatter or a format (where one can only specify a fixed number of fraction digits)?

Playground shows exactly what I want:

1
1
1
1.1
1.01
1.001

Using String(), String(describing:), .description or "\()" gives me:

1.0
1.0
1.0
1.1
1.01
1.001

So what is Playground using for its string conversion? I want that! ;)

This is what the Playground looks like


Solution

  • You could do something like this:

    extension FloatingPoint {
        var string: String {
            let result = "\(self)"
            return result.hasSuffix(".0") ? String(result.dropLast(2)) : result
        }
    }
    
    let one: Double = 1
    let alsoOne: Double = 1.0
    let oneAsWell: Double = 1.00
    let x: Double = 1.10
    let y: Double = 1.010
    let z: Double = 1.0010
    
    print(one.string)        // 1
    print(alsoOne.string)    // 1
    print(oneAsWell.string)  // 1
    print(x.string)          // 1.1
    print(y.string)          // 1.01
    print(z.string)          // 1.001