Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float value to String in Swift

Tags:

swift

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)

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)"

In swift 3 it is simple as given below

let stringFloat =  String(describing: float)

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.