Converting CGFloat to String in Swift
Asked Answered
W

3

37

This is my current way of converting a CGFloat to String in Swift:

let x:Float = Float(CGFloat)
let y:Int = Int(x)
let z:String = String(y)

Is there a more efficient way of doing this?

Wayzgoose answered 6/8, 2014 at 6:58 Comment(0)
S
85

You can use string interpolation:

let x: CGFloat = 0.1
let string = "\(x)" // "0.1"

Or technically, you can use the printable nature of CGFloat directly:

let string = x.description

The description property comes from it implementing the Printable protocol which is what makes string interpolation possible.

Silicic answered 6/8, 2014 at 7:0 Comment(0)
S
20

The fast way:

let x = CGFloat(12.345)
let s = String(format: "%.3f", Double(x))

The better way, because it takes care on locales:

let x = CGFloat(12.345)

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.minimumFractionDigits = 3
numberFormatter.maximumFractionDigits = 3

let s = numberFormatter.stringFromNumber(x)
Superscribe answered 6/8, 2014 at 7:3 Comment(0)
D
1

This worked for me let newstring = floatvalue.description

Diarchy answered 28/11, 2022 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.