Home > front end >  Unable to multiply two string values in swift
Unable to multiply two string values in swift

Time:06-23

I am getting float value in string format from JSON like below

JSON:

{
 "result": {

  "conversion_factor": {
        "conv_factor": "0.820000"
    }
    "search_result": [
        {
         "service_details": [
                {
                  "standard_rate_in_usd": "10.00",

now i need to multiply conv_factor * standard_rate_in_usd

code: with this code only first value coming correct remaining showing wrong why?

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)"
}
}

CodePudding user response:

You need to convert to floats:

let convResult = Float(oneSerdet.standard_rate_in_usd) * 
Float(searchResult?.result?.conversion_factor?.conv_factor)

CodePudding user response:

Try this, hope this will resolves your issue

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")
}

CodePudding user response:

You have multiple problems:

  1. Your construct searchResult?.result?.conversion_factor?.conv_factor evaluates to an Optional String: String?.

  2. You can't multiply strings. Strings are not numeric. You need to convert your string to a Double. But the Double initializer that takes a string also returns an Optional (since "Apple", for example, can't be converted to a Double.

Here is some sample code that will take 2 Optional Strings, try to convert them to Doubles, and multiples them.

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)

That outputs

246.912

  • Related