Search code examples
swiftstringformatnumber-formatting

Force character inclusion in string displaying


I am manually displaying a string printing a USD price as follows:

let price : String = String(format:"%.2f", finalPrice)
priceLabel.text = String("$" + price)

Is there any way to add the , every 3 digit without using NumberFormatter? I couldn't find the corresponding format code for that if any.


Solution

  • I would recommend to USE the NumberFormatter.

    Your code would look like this:

    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = Locale(identifier: "en_US")
    formatter.maximumFractionDigits = 2
    formatter.groupingSeparator = ","
    priceLabel.text = formatter.string(for: price)