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