Here is one way - based on the way you have shown how you want the values formatted:
func formatNumber(_ i: Int) -> String {
let nf = NumberFormatter()
nf.usesGroupingSeparator = true
nf.numberStyle = .decimal
var newNum: Double = 0
var numDec: Int = 0
var sPost: String = ""
switch i {
case 0..<10_000:
newNum = Double(i)
case 10_000..<100_000:
newNum = Double(i) / 1_000.0
numDec = 1
sPost = "K"
case 100_000..<1_000_000:
newNum = Double(i) / 1_000.0
sPost = "K"
case 1_000_000..<100_000_000:
newNum = Double(i) / 1_000_000.0
numDec = 1
sPost = "M"
default:
newNum = Double(i) / 1_000_000.0
sPost = "M"
}
nf.maximumFractionDigits = numDec
return (nf.string(for: newNum) ?? "0") + sPost
}
To check:
let a: [Int] = [
1234,
12345,
123456,
1234567,
12345678,
123456789
]
a.forEach { n in
print(formatNumber(n))
}
The Thousand and Decimal separators will be based on the default for the locale.
So, the debug output from that with a USA locale is:
1,234
12.3K
123K
1.2M
12.3M
123M
and, for example, with a Germany locale:
1.234
12,3K
123K
1,2M
12,3M
123M
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…