Precision String Format Specifier In Swift

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

    Power of extension

    extension Double {
        var asNumber:String {
            if self >= 0 {
                var formatter = NSNumberFormatter()
                formatter.numberStyle = .NoStyle
                formatter.percentSymbol = ""
                formatter.maximumFractionDigits = 1
                return "\(formatter.stringFromNumber(self)!)"
            }
            return ""
        }
    }
    
    let velocity:Float = 12.32982342034
    
    println("The velocity is \(velocity.toNumber)")
    

    Output: The velocity is 12.3

提交回复
热议问题