問題是我的API響應返回訂單[indexPath.row] .price作爲String。該字符串實際上是雙倍值,如3.55973455234。我需要將此值轉換爲3.56之類的內容並顯示在UI標籤中。自從早上起,我一直在拉我的頭髮來達到這個目的。爲什麼Swift在轉換時如此可怕?將字符串轉換爲Double然後返回字符串
cell.lblPayValue.text = orders[indexPath.row].price
問題是我的API響應返回訂單[indexPath.row] .price作爲String。該字符串實際上是雙倍值,如3.55973455234。我需要將此值轉換爲3.56之類的內容並顯示在UI標籤中。自從早上起,我一直在拉我的頭髮來達到這個目的。爲什麼Swift在轉換時如此可怕?將字符串轉換爲Double然後返回字符串
cell.lblPayValue.text = orders[indexPath.row].price
你也可以使用的NumberFormatter但你需要將其轉換回的NSNumber ...
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.locale = Locale(identifier: "en_US")
if let number = formatter.number(from: orders[indexPath.row].price) {
cell.lblPayValue.text = formatter.string(from: number)
}
但請不要創建n個的NumberFormatter。創建一個並將其存儲在某個地方。
只要做到這一點是這樣的:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if let price = Double(orders[indexPath.row].price), let formattedPrice = formatter.string(for: price) {
cell.lblPayValue.text = formattedPrice
}
cell.lblPayValue.text
Double
轉換是非常簡單的恕我直言。您可以通過使用帶字符串的初始化工具創建一個新的Double。然後你有一個可選的雙。然後可以將其轉換爲格式化的字符串。所以...
let price: String = "3.55973455234" // your price
let text = String(format: "%.2f", Double(price)!)
print(text) // prints 3.56
[檢查此答案](https://stackoverflow.com/q/41558832/335858),它可能有一個很好的解釋給你。 – dasblinkenlight