Precision String Format Specifier In Swift

前端 未结 30 1975
面向向阳花
面向向阳花 2020-11-22 05:58

Below is how I would have previously truncated a float to two decimal places

NSLog(@\" %.02f %.02f %.02f\", r, g, b);

I checked the docs an

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 06:34

    A more elegant and generic solution is to rewrite ruby / python % operator:

    // Updated for beta 5
    func %(format:String, args:[CVarArgType]) -> String {
        return NSString(format:format, arguments:getVaList(args))
    }
    
    "Hello %@, This is pi : %.2f" % ["World", M_PI]
    

提交回复
热议问题