Precision String Format Specifier In Swift

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

    Also with rounding:

    extension Float
    {
        func format(f: String) -> String
        {
            return NSString(format: "%\(f)f", self)
        }
        mutating func roundTo(f: String)
        {
            self = NSString(format: "%\(f)f", self).floatValue
        }
    }
    
    extension Double
    {
        func format(f: String) -> String
        {
            return NSString(format: "%\(f)f", self)
        }
        mutating func roundTo(f: String)
        {
            self = NSString(format: "%\(f)f", self).doubleValue
        }
    }
    
    x = 0.90695652173913
    x.roundTo(".2")
    println(x) //0.91
    

提交回复
热议问题