将字符串转换为Double然后返回字符串
问题描述:
问题是我的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
}
- 所以你第一次得到双重价值与IF-让
- 然后你使用它来设置你的
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