下面是我以前如何将浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我检查了文档和电子书,但无法弄清楚。谢谢!
到目前为止,我最好的解决方案:
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 的解决方案,将格式化操作直接绑定到数据类型。很可能某处有一个内置的格式化操作库,或者它很快就会发布。请记住,该语言仍处于测试阶段。