Precision String Format Specifier In Swift

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

    here a "pure" swift solution

     var d = 1.234567
    operator infix ~> {}
    @infix func ~> (left: Double, right: Int) -> String {
        if right == 0 {
            return "\(Int(left))"
        }
        var k = 1.0
        for i in 1..right+1 {
            k = 10.0 * k
        }
        let n = Double(Int(left*k)) / Double(k)
        return "\(n)"
    }
    println("\(d~>2)")
    println("\(d~>1)")
    println("\(d~>0)")
    

提交回复
热议问题