0

I want to convert a Float into a string.

myFloat: Float = 99.0
myString: String

How would I convert myFloat into a string so I can assign the following code

myString = myFloat
Shruti Thombre
  • 989
  • 4
  • 11
  • 27
Stephen Fox
  • 14,190
  • 19
  • 48
  • 52

2 Answers2

8

Similar to Connor's answer, you can do the following to have a little more control about how your Double or Float is dislpayed...

let myStringToTwoDecimals = String(format:"%.2f", myFloat)

This is basically like stringWithFormat in objC.

Ethan
  • 1,567
  • 11
  • 16
  • 1
    I found this because of the initializer patterns of Swift from ObjectiveC. `[NSString stringWithFormat:@"%.2f and %@", myFloat, @"I do this in my sleep"]` so I assumed that String(format:...) would be a valid initializer – Ethan Jul 29 '14 at 01:57
  • So, I can have a `println` with format (a little awkward) `println(String(format:"myFloat: %.2f", myFloat))`. – zaph Jul 29 '14 at 02:03
  • Yea dude, or you can like... accept change into your life ;) `println("full float value is \(myFloat)")` – Ethan Jul 29 '14 at 02:08
  • Sometimes I don't want "0.422535211267606", I just want "0.42" so I can read and comprehend the value easily. – zaph Jul 29 '14 at 02:49
  • You have reason. Here is another option, alternate to `println(String(format...))` specifically, David's answer is neat http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift – Ethan Jul 29 '14 at 03:10
0

You can use String Interpolation:

var myFloat: Float = 99.0
var myString: String = "\(myFloat)"
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142