Search code examples
swiftstringintegerconvertersseparator

How could i convert with an extension of NumberFormatter a String to a Float


I have created an extension of NumberFormatter and binaryInteger, to convert Int to String with a space between thousands like thise: 11111 -> 11 111 Now, in another place, i need to reverse the convertion from a specific string to a Float , like this: 11 111 -> 11111.

Here is the first extensions of NumberFormatter and BinaryInteger:

extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.groupingSeparator = " "
        formatter.allowsFloats = true
        formatter.numberStyle = .decimal
        return formatter
    }()
}

extension BinaryInteger {
    var formattedWithSeparator: String {
        return Formatter.withSeparator.string(for: self) ?? ""
    }
}

So, how could i code an another extension, to make the reverse process? thank you.


Solution

  • Try this:

    extension String {
        func backToFloat() -> Float {
          // Make a copy of original string
          var temp = self
    
          // Remove spaces
          temp.removeAll(where: { $0 == " " })
    
          return Float(temp) ?? 0.0
        }
    }
    
    print("1 234 567.2".backToFloat())
    // log: 1234567.2
    

    To enable Float -> String and Double -> String:

    extension FloatingPoint {
        var formattedWithSeparator: String {
            return Formatter.withSeparator.string(for: self) ?? ""
        }
    }
    
    print(12345678.12.formattedWithSeparator)
    // log: 12 345 678.12