Convert Int To String

For example, I want the value (for the purpose of a label) to display "." at one stage and a number a different stage.

Accepted Reply

You have lots of options:


     let n = 42
     let s1 = String (n)
     let s2 = "\(n)"
     let s3 = String (format: "%d", n)
     let s4 = NumberFormatter ().string (for: n)


Note that the third case (using a string format) is a bit treacherous if Int is 32 bits rather than 64 bits, but I don't think there are any current Apple platforms where it is 32 bits. Using a format is useful is you want to use a specifier that controls the number of digits displayed, padding, etc.


The fourth case is useful if you want localized formatting of the number.

Replies

You have lots of options:


     let n = 42
     let s1 = String (n)
     let s2 = "\(n)"
     let s3 = String (format: "%d", n)
     let s4 = NumberFormatter ().string (for: n)


Note that the third case (using a string format) is a bit treacherous if Int is 32 bits rather than 64 bits, but I don't think there are any current Apple platforms where it is 32 bits. Using a format is useful is you want to use a specifier that controls the number of digits displayed, padding, etc.


The fourth case is useful if you want localized formatting of the number.

I don't think there are any current Apple platforms where it is 32 bits.

That’s not quite true; watchOS is the last holdout.

The fourth case is useful if you want localized formatting of the number.

In that case you’re better off doing this:

let s4 = NumberFormatter.localizedString(from: n as NSNumber, number: .decimal)

Formatters tend to be heavyweight objects, so it’s better to cache them, and this convenience method does that caching for you.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"