Adding Thousand Separator to Int in Swift

后端 未结 7 1272
长发绾君心
长发绾君心 2020-11-30 05:17

I am fairly new to Swift and having a great deal of trouble finding a way to add a space as a thousand separator.

What I am hoping to achieve is taking the result

7条回答
  •  一生所求
    2020-11-30 05:47

    Leo Dabus's answer translated to Swift 3:

    Into any .swift file, out of a class:

    struct Number {
        static let withSeparator: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.groupingSeparator = " " // or possibly "." / ","
            formatter.numberStyle = .decimal
            return formatter
        }()
    }
    extension Integer {
        var stringWithSepator: String {
            return Number.withSeparator.string(from: NSNumber(value: hashValue)) ?? ""
        }
    }
    

    Usage:

    let myInteger = 2358000
    let myString = myInteger.stringWithSeparator  // "2 358 000"
    

提交回复
热议问题