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