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

后端 未结 3 1325
我寻月下人不归
我寻月下人不归 2021-01-05 02:38

I\'d like to change my large numbers from 100,000 to $100K if this is possible.

This is what I have so far:

let valueFormatter = NSN         


        
3条回答
  •  借酒劲吻你
    2021-01-05 03:02

    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
        }
    }
    

提交回复
热议问题