igouy
igouy

Reputation: 2692

Is there Swift 6 number formatting in string interpolation without "import Foundation"?

I like being able to do this:

print( "\("YYYY") \(454.90008)" ) 

but I want to do this:

print( "\("YYYY") \(String(format: "%.3f", 454.90008))" ) 

which will only compile with import Foundation

Is that correct or is there some Swift 6 numeric precision formatting that does not require Foundation?

Upvotes: -7

Views: 136

Answers (1)

Radioactive
Radioactive

Reputation: 688

Doing precision formatting while not importing Foundation is hard. I don't know why you don't want to import it, it's named Foundation and it is the foundation (not all of it). But you can create a custom implementation:

extension String {
    init(_ formatting: Double, precision: Int) {
        let string = String(formatting)
        
        precondition(precision >= 0, "Precision must be a positive number")
        
        let firstHalf = string.prefix { $0 != "." }
        var secondHalf = string
            .drop { $0 != "." }
            .prefix(precision + 1)
        
        secondHalf.popFirst()
        
        if secondHalf.count < precision {
            for _ in 0..<precision - secondHalf.count {
                secondHalf.append("0")
            }
        }
        
        self.init(stringLiteral: firstHalf + (secondHalf.isEmpty ? "" : ".")  + secondHalf)
    }
}

I used precondition to guard against negative numbers. It crashes even if you don't put precondition there. But you can also early exit via guard statement depending on your implementation.

guard precision >= 0 else {
    self.init(stringLiteral: "") 
    return
 }

Upvotes: 0

Related Questions