我从JSON中获得字符串格式的浮点值,如下
JSON:
{
"result": {
"conversion_factor": {
"conv_factor": "0.820000"
}
"search_result": [
{
"service_details": [
{
"standard_rate_in_usd": "10.00",
现在我需要乘以conv_factor * standard_rate_in_usd
代码:这段代码只有第一个值是正确的,剩下的显示错误,为什么?
let indexData = searchResult?.result?.search_result?[indexPath.row]
if let servDetls = indexData?.service_details{
for oneSerdet in servDetls{
var stringPrice: String?
if var priceVal = Float(oneSerdet.standard_rate_in_usd!), var convVal = Float((searchResult?.result?.conversion_factor?.conv_factor)!) {
stringPrice = String(priceVal * convVal)
}
else{
stringPrice = ""
}
cell.priceLbl.text = "£ (stringPrice ?? "") (currData)"
}
}
需要转换为浮点数:
let convResult = Float(oneSerdet.standard_rate_in_usd) *
Float(searchResult?.result?.conversion_factor?.conv_factor)
尝试一下,希望这将解决您的问题
if let conv_factor = oneSerdet.conv_factor,
let factor = Double(conv_factor),
let standard_rate_in_usd = oneSerdet.standard_rate_in_usd,
let usd = Double(standard_rate_in_usd) {
print(factor*usd)
cell.priceLbl.text = "(factor*usd)"
}else{
cell.priceLbl.text = ""
print("Unreachable")
}
你有很多问题:
-
您的结构
searchResult?.result?.conversion_factor?.conv_factor
计算为可选字符串:String?
. -
字符串不能相乘。字符串不是数字。您需要将字符串转换为Double类型。但是接受字符串的Double初始化式也返回一个Optional类型(因为"Apple"不能转换为Double类型)。
下面是一些示例代码,将接受2个可选字符串,尝试将它们转换为double,并将它们相乘。
let xString: String? = "123.456"
let yString: String? = "2.0"
let x = xString.map { Double($0) ?? 0 } ?? 0.0
let y = yString.map { Double($0) ?? 0 } ?? 0.0
let result: Double = x * y
print(result)
输出246.912