58

I want to convert -33.861382,151.210316,226.76 to String. I tried to type cast it but was unscucessful. How to convert float value to String ?

Cezar
  • 55,636
  • 19
  • 86
  • 87
iOS
  • 5,450
  • 5
  • 23
  • 25
  • possible duplicate of [Precision String Format Specifier In Swift](http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift) – trojanfoe Jun 09 '14 at 15:18
  • possible duplicate of [String formatting of a Double](http://stackoverflow.com/questions/24047374/string-formatting-of-a-double) – Jukka Suomela Jun 12 '14 at 21:52

5 Answers5

67

If you want some more control of how it's converted you can either use +stringWithFormat on NSString or NSNumberFormatter

let f = -33.861382
let s = NSString(format: "%.2f", f)

let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
// Configure the number formatter to your liking
let s2 = nf.stringFromNumber(f)
hallski
  • 123,625
  • 4
  • 33
  • 21
44

Using Xcode 6.3 you can convert a float to a string using .description

var float = -33.861382
var string = "my float is " + float.description

or you could let swift do it for you using:

var string = "my float is \(float)"
Richard Torcato
  • 2,504
  • 25
  • 26
25

In swift 3 it is simple as given below

let stringFloat =  String(describing: float)
Sebin Roy
  • 834
  • 9
  • 10
3

Here is the simple example in Swift 3.0 for convert your NSNumber into String with decimal using NumberFormatter and if you want to know more about formatter then link here

let num = NSNumber(value: 8.800000000000001)
let formatter : NumberFormatter = NumberFormatter()
formatter.numberStyle = .decimal
let str = formatter.string(from: num)!
print(str)

Output :

8.8

Any query according to my code then put comment.

Alexander Volkov
  • 7,904
  • 1
  • 47
  • 44
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
-4

Directly from page 6 of the swift programming reference available from developer.apple.com:

Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

OR

There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash () before the parentheses. For example:

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

scodav
  • 75
  • 7