Precision String Format Specifier In Swift

2018-12-31 08:29发布

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 and the eBook but haven't been able to figure it out. Thanks!

标签: swift
29条回答
查无此人
2楼-- · 2018-12-31 08:55

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)")
查看更多
路过你的时光
3楼-- · 2018-12-31 08:57

A version of Vincent Guerci's ruby / python % operator, updated for Swift 2.1:

func %(format:String, args:[CVarArgType]) -> String {
  return String(format:format, arguments:args)
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]
查看更多
泛滥B
4楼-- · 2018-12-31 09:00

I found String.localizedStringWithFormat to work quite well:

Example:

let value: Float = 0.33333
let unit: String = "mph"

yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
查看更多
孤独寂梦人
5楼-- · 2018-12-31 09:00

Most answers here are valid. However, in case you will format the number often, consider extending the Float class to add a method that returns a formatted string. See example code below. This one achieves the same goal by using a number formatter and extension.

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NSNumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.stringFromNumber(self) ?? "\(self)"
    }
}

let myVelocity:Float = 12.32982342034

println("The velocity is \(myVelocity.string(2))")
println("The velocity is \(myVelocity.string(1))")

The console shows:

The velocity is 12.33
The velocity is 12.3

SWIFT 3.1 update

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}
查看更多
梦醉为红颜
6楼-- · 2018-12-31 09:00

Swift2 example: Screen width of iOS device formatting the Float removing the decimal

print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))
查看更多
君临天下
7楼-- · 2018-12-31 09:02

A more elegant and generic solution is to rewrite ruby / python % operator:

// Updated for beta 5
func %(format:String, args:[CVarArgType]) -> String {
    return NSString(format:format, arguments:getVaList(args))
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]
查看更多
登录 后发表回答