NSNumberFormatter : Show 'k' instead of ',000' in large numbers?

こ雲淡風輕ζ 提交于 2019-11-30 19:58:30

edit/update

Swift 3 or later

extension FloatingPoint {
    var kFormatted: String {
        return String(format: self >= 1000 ? "$%.0fK" : "$%.0f", (self >= 1000 ? self/1000 : self) as! CVarArg )
    }
}

The you can use it like this to format your output:

10.0.kFormatted     // "$10"
100.0.kFormatted    // "$100"
1000.0.kFormatted   // "$1K"
10000.0.kFormatted  // "$10K"
162000.0.kFormatted  // "$162K"
153000.0.kFormatted  // "$153K"
144000.0.kFormatted  // "$144K"
135000.0.kFormatted  // "$135K"
126000.0.kFormatted  // "$126K"
f1024

I've bumped into the same issue and solved it by implementing a custom formatter. Just started coding in Swift, so the code might not be the most idiomatic.

open class KNumberFormatter : NumberFormatter {
    override open func string(for obj: Any?) -> String? {
        if let num = obj as? NSNumber {
            let suffixes = ["", "k", "M", "B"]
            var idx = 0
            var d = num.doubleValue
            while idx < 4 && abs(d) >= 1000.0 {
                d /= 1000.0
                idx += 1
            }
            var currencyCode = ""
            if self.currencySymbol != nil {
                currencyCode = self.currencySymbol!
            }

            let numStr = String(format: "%.1f", d)

            return currencyCode + numStr + suffixes[idx]
        }
        return nil
    }
}

I think you can add an extension to NSNumberFormatter. Try the following, I didn't test it so let me know in the comment if it needs to be edited

extension NSNumberFormatter {
    func dividedByK(number: Int)->String{
        if (number % 1000) == 0 {
            let numberK = Int(number / 1000)
            return "\(numberK)K"
        }
        return "\(number)"
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!