Swift double to string
It is not casting, it is creating a string from a value with a format.
let a: Double = 1.5
let b: String = String(format: "%f", a)
print("b: \(b)") // b: 1.500000
With a different format:
let c: String = String(format: "%.1f", a)
print("c: \(c)") // c: 1.5
You can also omit the format
property if no formatting is needed.
let double = 1.5
let string = double.description
update Xcode 7.1 • Swift 2.1:
Now Double is also convertible to String so you can simply use it as you wish:
let double = 1.5
let doubleString = String(double) // "1.5"
Swift 3 or later we can extend LosslessStringConvertible
and make it generic
Xcode 11.3 • Swift 5.1 or later
extension LosslessStringConvertible {
var string: String { .init(self) }
}
let double = 1.5
let string = double.string // "1.5"
For a fixed number of fraction digits we can extend FloatingPoint
protocol:
extension FloatingPoint where Self: CVarArg {
func fixedFraction(digits: Int) -> String {
.init(format: "%.*f", digits, self)
}
}
If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter
:
extension Formatter {
static let number = NumberFormatter()
}
extension FloatingPoint {
func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
2.12345.fractionDigits() // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up) // "2.124"
In addition to @Zaph's answer, you can create an extension
on Double
:
extension Double {
func toString() -> String {
return String(format: "%.1f",self)
}
}
Usage:
var a:Double = 1.5
println("output: \(a.toString())") // output: 1.5