Precision String Format Specifier In Swift

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

    import Foundation
    
    extension CGFloat {
        var string1: String {
            return String(format: "%.1f", self)
        }
        var string2: String {
            return String(format: "%.2f", self)
        }
    }
    

    Usage

    let offset = CGPoint(1.23, 4.56)
    print("offset: \(offset.x.string1) x \(offset.y.string1)")
    // offset: 1.2 x 4.6
    

提交回复
热议问题