2017-10-16 217 views
0

問題是我的API響應返回訂單[indexPath.row] .price作爲String。該字符串實際上是雙倍值,如3.55973455234。我需要將此值轉換爲3.56之類的內容並顯示在UI標籤中。自從早上起,我一直在拉我的頭髮來達到這個目的。爲什麼Swift在轉換時如此可怕?將字符串轉換爲Double然後返回字符串

 cell.lblPayValue.text = orders[indexPath.row].price 
+0

[檢查此答案](https://stackoverflow.com/q/41558832/335858),它可能有一個很好的解釋給你。 – dasblinkenlight

回答

1

你也可以使用的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。創建一個並將其存儲在某個地方。

+0

嘿它似乎沒有擊中if語句我們可以做些什麼,以便它總是在if區塊內? – Ackman

+0

可能是小數點分隔符的問題。解析時,區域設置應始終設置正確。 – Sulthan

+0

也許您的號碼採用與區域設置不同的方式進行格式化(因爲NumberFormatter是區域設置特定的)。嘗試使用更新的代碼。無論如何,儘量不要使用這個解決方案,因爲你會創建*也許*不必要的資源。但NumberFormatter仍然提供一些優勢。 – McNight

1

只要做到這一點是這樣的:

let formatter = NumberFormatter() 
formatter.numberStyle = .currency 

if let price = Double(orders[indexPath.row].price), let formattedPrice = formatter.string(for: price) { 
    cell.lblPayValue.text = formattedPrice 
} 
  1. 所以你第一次得到雙重價值與IF-讓
  2. 然後你使用它來設置你的cell.lblPayValue.text
  3. 您使用格式化程序獲取您的貨幣格式Double
+0

沒有。不設置任何值。 – Ackman

+0

你確定'orders [indexPath.row] .price'有一個有效的double嗎?用'NumberFormatter –

+0

檢查更新的答案btw不需要再投射到'NSNumber'。該業務指出,「價格」是一個字符串。 – Sulthan

1

轉換是非常簡單的恕我直言。您可以通過使用帶字符串的初始化工具創建一個新的Double。然後你有一個可選的雙。然後可以將其轉換爲格式化的字符串。所以...

let price: String = "3.55973455234" // your price 
    let text = String(format: "%.2f", Double(price)!) 
    print(text) // prints 3.56 
相關問題