下面是我以前如何将一个浮点数截断到小数点后两位

NSLog(@" %.02f %.02f %.02f", r, g, b);

我查了文档和电子书,但还没找到答案。谢谢!


当前回答

你还不能用字符串插值来做。你最好的选择仍然是NSString格式化:

println(NSString(format:"%.2f", sqrt(2.0)))

从python中推断,合理的语法可能是:

@infix func % (value:Double, format:String) -> String {
    return NSString(format:format, value)
}

然后允许你使用它们作为:

M_PI % "%5.3f"                // "3.142"

你可以为所有的数字类型定义类似的操作符,不幸的是我还没有找到一种方法来使用泛型。

Swift 5更新

至少在Swift 5中,String直接支持format: initializer,所以不需要使用NSString, @infix属性也不再需要,这意味着上面的示例应该写成:

println(String(format:"%.2f", sqrt(2.0)))

func %(value:Double, format:String) -> String {
    return String(format:format, value)
}

Double.pi % "%5.3f"         // "3.142"

其他回答

这里有一个“纯粹的”快速解决方案

 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)")

使用以下方法

let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)

println(output)
extension Double {
  func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
     let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
     return Double(formattedString)!
     }
 }

 1.3333.formatWithDecimalPlaces(2)

你仍然可以在Swift中使用NSLog,就像在Objective-C中一样,只是没有@符号。

NSLog("%.02f %.02f %.02f", r, g, b)

编辑:在与Swift合作一段时间后,我想添加这个变化

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")

输出:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4

也用于四舍五入:

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