Swift number formatting

前端 未结 4 1107
深忆病人
深忆病人 2021-02-08 08:10

I am just starting to get to know Swift but I am having a serious problem with number formatting at an extremely basic level.

For example, I need to display an integer w

4条回答
  •  春和景丽
    2021-02-08 08:34

    Here's a POP solution to the problem:

    protocol Formattable {
        func format(pattern: String) -> String
    }
    extension Formattable where Self: CVarArg {
        func format(pattern: String) -> String {
            return String(format: pattern, arguments: [self])
        }
    }
    extension Int: Formattable { }
    extension Double: Formattable { }
    extension Float: Formattable { }
    
    let myInt = 10
    let myDouble: Double = 0.01
    let myFloat: Float = 1.11
    
    print(myInt.format(pattern: "%04d"))      // "0010
    print(myDouble.format(pattern: "%.2f"))   // "0.01"
    print(myFloat.format(pattern: "$%03.2f")) // "$1.11"
    print(100.format(pattern: "%05d"))        // "00100"
    

提交回复
热议问题