-1

How can I change high numbers to something like:

1,000 = 1K
1,250 = 1,2K
10,200 = 10,2K
102,000 = 102K
1,200,000 = 1,2M

Or something like that?

This is how I set the number:

textCell?.ll1.text = "\(String(thumb[indexPath.row].count))"
textCell?.ll2.text = "\(String(love[indexPath.row].count))"
Sibling Thor
  • 57
  • 1
  • 6

2 Answers2

1
let formatter = NSByteCountFormatter()

That's it ;)

Examples:

let oneFormattedNumber = formatter.stringFromByteCount(1025000000000)
let formattedList = [1_000, 1_250, 10_200, 102_000, 1_200_000].map(formatter.stringFromByteCount)
NiñoScript
  • 4,523
  • 2
  • 27
  • 33
0

You can add this functionality as an extension to Int:

extension Int {
  func shortLiteralDescription() -> String {
        var factor = 0
        let tokens = ["","K", "M", "G","T","P"] //If you think you will need to express more, add them here
        var value = Double(self);
        while (value > 1000) {
            value /= 1000
            factor++
        }
        return "\(value)\(tokens[factor])"
    }
}

And then:

400200.shortLiteralDescription()   //400.2K
4000.shortLiteralDescription()     //4.0K
Hugo Alonso
  • 6,684
  • 2
  • 34
  • 65