Swift double to string

2019-01-03 15:29发布

Before i updated xCode 6, I had no problems casting a double to a string bur now it gives me error

var a: Double = 1.5
var b: String = String(a)

It gives me the error message "double is not convertible to string". Is there any other way to do it?

11条回答
看我几分像从前
2楼-- · 2019-01-03 15:40

In addition to @Zaph answer, you can create extension:

extension Double {
    func toString() -> String {
        return String(format: "%.1f",self)
    }
}

Usage:

var a:Double = 1.5
println("output: \(a.toString())")  // output: 1.5
查看更多
在下西门庆
3楼-- · 2019-01-03 15:43

This function will let you specify the number of decimal places to show:

func doubleToString(number:Double, numberOfDecimalPlaces:Int) -> String {
    return String(format:"%."+numberOfDecimalPlaces.description+"f", number)
}

Usage:

let numberString = doubleToStringDecimalPlacesWithDouble(number: x, numberOfDecimalPlaces: 2)
查看更多
可以哭但决不认输i
4楼-- · 2019-01-03 15:46
let myDouble = 1.5 
let myString = myDouble.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 myDouble = 1.5
let myDoubleString = String(myDouble)   // "1.5"

Xcode 8.3.2 • Swift 3.1:

for fixed number of fraction digits you can also extend Double:

extension FloatingPoint {
    func fixedFraction(digits: Int) -> String {
        return String(format: "%.\(digits)f", self as! CVarArg)
    }
}

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"
查看更多
叛逆
5楼-- · 2019-01-03 15:46

Swift 4: Use following code

let number = 2.4
let string = String(format: "%.2f", number)
查看更多
叼着烟拽天下
6楼-- · 2019-01-03 15:47
var b = String(stringInterpolationSegment: a)

This works for me. You may have a try

查看更多
狗以群分
7楼-- · 2019-01-03 15:49

to make anything a string in swift except maybe enum values simply do what you do in the println() method

for example:

var stringOfDBL = "\(myDouble)"
查看更多
登录 后发表回答