Precision String Format Specifier In Swift

前端 未结 30 2481
面向向阳花
面向向阳花 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:09

    I don't know about two decimal places, but here's how you can print floats with zero decimal places, so I'd imagine that can be 2 place, 3, places ... (Note: you must convert CGFloat to Double to pass to String(format:) or it will see a value of zero)

    func logRect(r: CGRect, _ title: String = "") {
        println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
            Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
    }
    

提交回复
热议问题