SWIFT中的精確字符串格式規范下面是我以前如何將浮點數截斷為小數點后兩位NSLog(@" %.02f %.02f %.02f", r, g, b);我檢查了文檔和電子書,但還沒有弄清楚。謝謝!
3 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
import Foundationextension 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 004let 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

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
String.localizedStringWithFormat
let value: Float = 0.33333let unit: String = "mph"yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
- 3 回答
- 0 關注
- 637 瀏覽
添加回答
舉報
0/150
提交
取消