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

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

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


当前回答

Swift2示例:iOS设备的屏幕宽度格式化浮点数去除小数

print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))

其他回答

也用于四舍五入:

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

你还不能用字符串插值来做。你最好的选择仍然是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"

少打字方式:

func fprint(format: String, _ args: CVarArgType...) {
    print(NSString(format: format, arguments: getVaList(args)))
}

我目前为止最好的解决方案,以下是David的回答:

import Foundation

extension Int {
    func format(f: String) -> String {
        return String(format: "%\(f)d", self)
    }
}

extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

let someInt = 4, someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004

let someDouble = 3.14159265359, someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142

我认为这是最类似swift的解决方案,将格式化操作直接绑定到数据类型上。很可能在某个地方有一个内置的格式化操作库,或者它很快就会发布。请记住,该语言仍处于测试阶段。

您也可以用这种方式创建操作符

operator infix <- {}

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

let str = "%d %.1f" <- [1453, 1.123]