Search code examples
iosswiftuilabelcurrency

Convert String to Double and then back to String


The problem is my API response returns orders[indexPath.row].price as a String. The string is actually a double value like 3.55973455234. I need to convert this value to something like 3.56 and display in UI label. I have been pulling my hair since morning to achieve this. Why is Swift so horrible at conversions?

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

Solution

  • You could also use NumberFormatter but you would need to convert it back to a 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)
    }
    

    But please don't create N NumberFormatter. Create one and store it somewhere.