0

I want to show a number in my app, and to keep it pretty, display leading zeros to make the layout even.

For example

000 500 / 500 000
001 000 / 500 000
100 350 / 500 000

I get the first number from an Int, and I want to format it into a string. Is there a neat way to assure that a number is always six digits, and also get the range of the leading zeros to format them differently?

Oscar Apeland
  • 6,422
  • 7
  • 44
  • 92
  • 1
    Use `NSNumberFormatter`. – rmaddy Oct 08 '16 at 16:11
  • @MartinR Understood which is why my first comment is to use `NSNumberFormatter` so the number looks correct for a given locale. – rmaddy Oct 08 '16 at 16:17
  • The 3-digit separator is localized to whitespace? Or intentionally chosen independently on the locale? Just following the locale may not be what the OP requires. – OOPer Oct 08 '16 at 16:37
  • @OOPer That can be dealt with by setting up the `NSNumberFormatter` properly. – rmaddy Oct 08 '16 at 23:16
  • @rmaddy, then you insist that all `NSNumberFormatter` related questions needs be in a single thread? – OOPer Oct 08 '16 at 23:25
  • @OOPer How did you come to that conclusion? I simply posted a comment suggesting using `NSNumberFormatter`. I didn't post an answer, just a suggestion to point the OP in a direction. – rmaddy Oct 08 '16 at 23:27
  • @rmaddy, you are the one who marked this question as duplicate. – OOPer Oct 08 '16 at 23:29

2 Answers2

3

NSNumberFormatter has everything that you needs:

let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 6
formatter.numberStyle = .decimal

print(formatter.string(from: 500)!)
print(formatter.string(from: 1000)!)
print(formatter.string(from: 100_350)!)
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Don't set a specific separator. Leave the locale's default so each user sees the proper format but with leading zeros. – rmaddy Oct 08 '16 at 16:18
  • Also, NumberFormatter doesn't have an thousandSeparator property.. – Oscar Apeland Oct 08 '16 at 16:21
  • I'm using the OS X SDK so `thousandSeparator` is still there. Not realizing that it's the old (pre-10.4) way of doing things. Use `groupingSeparator` instead – Code Different Oct 08 '16 at 16:26
1

How about this?

String extension:

extension String {
    func substring(startIndex: Int, length: Int) -> String {
        let start = self.startIndex.advancedBy(startIndex)
        let end = self.startIndex.advancedBy(startIndex + length)
        return self[start..<end]
    }
}

usage:

var a = 500
var s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))

a = 500000
s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))

a = 50
s = "000000\(a)"
print(s.substring(s.characters.count - 6, length: 6))
Enix
  • 4,415
  • 1
  • 24
  • 37