-1

I am trying to convert a double, value to a string. This string will be set as the text of a Cocoa Touch UI element, that only accepts strings (I can't use the double as-is)

let value = example double value (my actual code is not this)
UIElementBeingSet.text = NSString(value)

When I try the above code, I get "Use of unresolved identifier 'value'.

Through my research, I have found questions like this, which seem to be asking similar things, but that question and similar ones involve limiting precision, don't involve UI elememts (which I am asking about), and are just overall not the answers I need.

Sorry for a basic question, and thanks!

Community
  • 1
  • 1
rocket101
  • 7,369
  • 11
  • 45
  • 64
  • For a lot more info on string formatting, see [this thread](http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift/24052438#24052438) – David Berry Aug 26 '14 at 19:10

2 Answers2

2

To use standard string formatting use format:

let d = 1.0 / 3.0
let s = String(format: "%0.3f", d)
println("s: \(s)")

Output:

s: 0.333

or

let s = String(format: "%0.16f", d)
println("s: \(s)")

Output:

s: 0.3333333333333333

String interpolation does not allow any control over the presentation, it is good for logging but severly lacking for presentation to a user.

zaph
  • 111,848
  • 21
  • 189
  • 228
1

Use string interpolation:

let d: Double = 1 / 3
let x = "\(d)"

If you try that in a playground, it will print:

"0.333333333333333"

Read more about string interpolation

Antonio
  • 71,651
  • 11
  • 148
  • 165