SwiftUIの基本を身につけたい方はこちら

【Swift】カンマ区切り

extension String {
    func withComma() -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.groupingSeparator = ","
        formatter.groupingSize = 3
        let number = formatter.number(from: self)
        return formatter.string(from: number ?? 0)
    }
}

let price = "123456"
let formattedPrice = price.withComma()
print(formattedPrice) // "123,456"

評価