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

后端 未结 3 1328
我寻月下人不归
我寻月下人不归 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:13

    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"
    

提交回复
热议问题